PageRenderTime 30ms CodeModel.GetById 18ms app.highlight 8ms RepoModel.GetById 2ms app.codeStats 0ms

/framework/validators/Validator.php

https://gitlab.com/hostingvk4/yii2
PHP | 368 lines | 137 code | 18 blank | 213 comment | 22 complexity | 048e1f211673993524ace362a6988856 MD5 | raw file
  1<?php
  2/**
  3 * @link http://www.yiiframework.com/
  4 * @copyright Copyright (c) 2008 Yii Software LLC
  5 * @license http://www.yiiframework.com/license/
  6 */
  7
  8namespace yii\validators;
  9
 10use Yii;
 11use yii\base\Component;
 12use yii\base\NotSupportedException;
 13
 14/**
 15 * Validator is the base class for all validators.
 16 *
 17 * Child classes should override the [[validateValue()]] and/or [[validateAttribute()]] methods to provide the actual
 18 * logic of performing data validation. Child classes may also override [[clientValidateAttribute()]]
 19 * to provide client-side validation support.
 20 *
 21 * Validator declares a set of [[builtInValidators|built-in validators] which can
 22 * be referenced using short names. They are listed as follows:
 23 *
 24 * - `boolean`: [[BooleanValidator]]
 25 * - `captcha`: [[\yii\captcha\CaptchaValidator]]
 26 * - `compare`: [[CompareValidator]]
 27 * - `date`: [[DateValidator]]
 28 * - `default`: [[DefaultValueValidator]]
 29 * - `double`: [[NumberValidator]]
 30 * - `each`: [[EachValidator]]
 31 * - `email`: [[EmailValidator]]
 32 * - `exist`: [[ExistValidator]]
 33 * - `file`: [[FileValidator]]
 34 * - `filter`: [[FilterValidator]]
 35 * - `image`: [[ImageValidator]]
 36 * - `in`: [[RangeValidator]]
 37 * - `integer`: [[NumberValidator]]
 38 * - `match`: [[RegularExpressionValidator]]
 39 * - `required`: [[RequiredValidator]]
 40 * - `safe`: [[SafeValidator]]
 41 * - `string`: [[StringValidator]]
 42 * - `trim`: [[FilterValidator]]
 43 * - `unique`: [[UniqueValidator]]
 44 * - `url`: [[UrlValidator]]
 45 *
 46 * @author Qiang Xue <qiang.xue@gmail.com>
 47 * @since 2.0
 48 */
 49class Validator extends Component
 50{
 51    /**
 52     * @var array list of built-in validators (name => class or configuration)
 53     */
 54    public static $builtInValidators = [
 55        'boolean' => 'yii\validators\BooleanValidator',
 56        'captcha' => 'yii\captcha\CaptchaValidator',
 57        'compare' => 'yii\validators\CompareValidator',
 58        'date' => 'yii\validators\DateValidator',
 59        'default' => 'yii\validators\DefaultValueValidator',
 60        'double' => 'yii\validators\NumberValidator',
 61        'each' => 'yii\validators\EachValidator',
 62        'email' => 'yii\validators\EmailValidator',
 63        'exist' => 'yii\validators\ExistValidator',
 64        'file' => 'yii\validators\FileValidator',
 65        'filter' => 'yii\validators\FilterValidator',
 66        'image' => 'yii\validators\ImageValidator',
 67        'in' => 'yii\validators\RangeValidator',
 68        'integer' => [
 69            'class' => 'yii\validators\NumberValidator',
 70            'integerOnly' => true,
 71        ],
 72        'match' => 'yii\validators\RegularExpressionValidator',
 73        'number' => 'yii\validators\NumberValidator',
 74        'required' => 'yii\validators\RequiredValidator',
 75        'safe' => 'yii\validators\SafeValidator',
 76        'string' => 'yii\validators\StringValidator',
 77        'trim' => [
 78            'class' => 'yii\validators\FilterValidator',
 79            'filter' => 'trim',
 80            'skipOnArray' => true,
 81        ],
 82        'unique' => 'yii\validators\UniqueValidator',
 83        'url' => 'yii\validators\UrlValidator',
 84    ];
 85    /**
 86     * @var array|string attributes to be validated by this validator. For multiple attributes,
 87     * please specify them as an array; for single attribute, you may use either a string or an array.
 88     */
 89    public $attributes = [];
 90    /**
 91     * @var string the user-defined error message. It may contain the following placeholders which
 92     * will be replaced accordingly by the validator:
 93     *
 94     * - `{attribute}`: the label of the attribute being validated
 95     * - `{value}`: the value of the attribute being validated
 96     *
 97     * Note that some validators may introduce other properties for error messages used when specific
 98     * validation conditions are not met. Please refer to individual class API documentation for details
 99     * about these properties. By convention, this property represents the primary error message
100     * used when the most important validation condition is not met.
101     */
102    public $message;
103    /**
104     * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
105     * please specify them as an array; for single scenario, you may use either a string or an array.
106     */
107    public $on = [];
108    /**
109     * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
110     * please specify them as an array; for single scenario, you may use either a string or an array.
111     */
112    public $except = [];
113    /**
114     * @var boolean whether this validation rule should be skipped if the attribute being validated
115     * already has some validation error according to some previous rules. Defaults to true.
116     */
117    public $skipOnError = true;
118    /**
119     * @var boolean whether this validation rule should be skipped if the attribute value
120     * is null or an empty string.
121     */
122    public $skipOnEmpty = true;
123    /**
124     * @var boolean whether to enable client-side validation for this validator.
125     * The actual client-side validation is done via the JavaScript code returned
126     * by [[clientValidateAttribute()]]. If that method returns null, even if this property
127     * is true, no client-side validation will be done by this validator.
128     */
129    public $enableClientValidation = true;
130    /**
131     * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
132     * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
133     * of the callable should be `function ($value)` which returns a boolean indicating
134     * whether the value is empty.
135     */
136    public $isEmpty;
137    /**
138     * @var callable a PHP callable whose return value determines whether this validator should be applied.
139     * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
140     * refer to the model and the attribute currently being validated. The callable should return a boolean value.
141     *
142     * This property is mainly provided to support conditional validation on the server side.
143     * If this property is not set, this validator will be always applied on the server side.
144     *
145     * The following example will enable the validator only when the country currently selected is USA:
146     *
147     * ```php
148     * function ($model) {
149     *     return $model->country == Country::USA;
150     * }
151     * ```
152     *
153     * @see whenClient
154     */
155    public $when;
156    /**
157     * @var string a JavaScript function name whose return value determines whether this validator should be applied
158     * on the client side. The signature of the function should be `function (attribute, value)`, where
159     * `attribute` is the name of the attribute being validated and `value` the current value of the attribute.
160     *
161     * This property is mainly provided to support conditional validation on the client side.
162     * If this property is not set, this validator will be always applied on the client side.
163     *
164     * The following example will enable the validator only when the country currently selected is USA:
165     *
166     * ```php
167     * function (attribute, value) {
168     *     return $('#country').value == 'USA';
169     * }
170     * ```
171     *
172     * @see when
173     */
174    public $whenClient;
175
176
177    /**
178     * Creates a validator object.
179     * @param mixed $type the validator type. This can be a built-in validator name,
180     * a method name of the model class, an anonymous function, or a validator class name.
181     * @param \yii\base\Model $model the data model to be validated.
182     * @param array|string $attributes list of attributes to be validated. This can be either an array of
183     * the attribute names or a string of comma-separated attribute names.
184     * @param array $params initial values to be applied to the validator properties
185     * @return Validator the validator
186     */
187    public static function createValidator($type, $model, $attributes, $params = [])
188    {
189        $params['attributes'] = $attributes;
190
191        if ($type instanceof \Closure || $model->hasMethod($type)) {
192            // method-based validator
193            $params['class'] = __NAMESPACE__ . '\InlineValidator';
194            $params['method'] = $type;
195        } else {
196            if (isset(static::$builtInValidators[$type])) {
197                $type = static::$builtInValidators[$type];
198            }
199            if (is_array($type)) {
200                $params = array_merge($type, $params);
201            } else {
202                $params['class'] = $type;
203            }
204        }
205
206        return Yii::createObject($params);
207    }
208
209    /**
210     * @inheritdoc
211     */
212    public function init()
213    {
214        parent::init();
215        $this->attributes = (array) $this->attributes;
216        $this->on = (array) $this->on;
217        $this->except = (array) $this->except;
218    }
219
220    /**
221     * Validates the specified object.
222     * @param \yii\base\Model $model the data model being validated
223     * @param array|null $attributes the list of attributes to be validated.
224     * Note that if an attribute is not associated with the validator,
225     * it will be ignored.
226     * If this parameter is null, every attribute listed in [[attributes]] will be validated.
227     */
228    public function validateAttributes($model, $attributes = null)
229    {
230        if (is_array($attributes)) {
231            $attributes = array_intersect($this->attributes, $attributes);
232        } else {
233            $attributes = $this->attributes;
234        }
235        foreach ($attributes as $attribute) {
236            $skip = $this->skipOnError && $model->hasErrors($attribute)
237                || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
238            if (!$skip) {
239                if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
240                    $this->validateAttribute($model, $attribute);
241                }
242            }
243        }
244    }
245
246    /**
247     * Validates a single attribute.
248     * Child classes must implement this method to provide the actual validation logic.
249     * @param \yii\base\Model $model the data model to be validated
250     * @param string $attribute the name of the attribute to be validated.
251     */
252    public function validateAttribute($model, $attribute)
253    {
254        $result = $this->validateValue($model->$attribute);
255        if (!empty($result)) {
256            $this->addError($model, $attribute, $result[0], $result[1]);
257        }
258    }
259
260    /**
261     * Validates a given value.
262     * You may use this method to validate a value out of the context of a data model.
263     * @param mixed $value the data value to be validated.
264     * @param string $error the error message to be returned, if the validation fails.
265     * @return boolean whether the data is valid.
266     */
267    public function validate($value, &$error = null)
268    {
269        $result = $this->validateValue($value);
270        if (empty($result)) {
271            return true;
272        }
273
274        list($message, $params) = $result;
275        $params['attribute'] = Yii::t('yii', 'the input value');
276        $params['value'] = is_array($value) ? 'array()' : $value;
277        $error = Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
278
279        return false;
280    }
281
282    /**
283     * Validates a value.
284     * A validator class can implement this method to support data validation out of the context of a data model.
285     * @param mixed $value the data value to be validated.
286     * @return array|null the error message and the parameters to be inserted into the error message.
287     * Null should be returned if the data is valid.
288     * @throws NotSupportedException if the validator does not supporting data validation without a model
289     */
290    protected function validateValue($value)
291    {
292        throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
293    }
294
295    /**
296     * Returns the JavaScript needed for performing client-side validation.
297     *
298     * You may override this method to return the JavaScript validation code if
299     * the validator can support client-side validation.
300     *
301     * The following JavaScript variables are predefined and can be used in the validation code:
302     *
303     * - `attribute`: the name of the attribute being validated.
304     * - `value`: the value being validated.
305     * - `messages`: an array used to hold the validation error messages for the attribute.
306     * - `deferred`: an array used to hold deferred objects for asynchronous validation
307     *
308     * @param \yii\base\Model $model the data model being validated
309     * @param string $attribute the name of the attribute to be validated.
310     * @param \yii\web\View $view the view object that is going to be used to render views or view files
311     * containing a model form with this validator applied.
312     * @return string the client-side validation script. Null if the validator does not support
313     * client-side validation.
314     * @see \yii\widgets\ActiveForm::enableClientValidation
315     */
316    public function clientValidateAttribute($model, $attribute, $view)
317    {
318        return null;
319    }
320
321    /**
322     * Returns a value indicating whether the validator is active for the given scenario and attribute.
323     *
324     * A validator is active if
325     *
326     * - the validator's `on` property is empty, or
327     * - the validator's `on` property contains the specified scenario
328     *
329     * @param string $scenario scenario name
330     * @return boolean whether the validator applies to the specified scenario.
331     */
332    public function isActive($scenario)
333    {
334        return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
335    }
336
337    /**
338     * Adds an error about the specified attribute to the model object.
339     * This is a helper method that performs message selection and internationalization.
340     * @param \yii\base\Model $model the data model being validated
341     * @param string $attribute the attribute being validated
342     * @param string $message the error message
343     * @param array $params values for the placeholders in the error message
344     */
345    public function addError($model, $attribute, $message, $params = [])
346    {
347        $value = $model->$attribute;
348        $params['attribute'] = $model->getAttributeLabel($attribute);
349        $params['value'] = is_array($value) ? 'array()' : $value;
350        $model->addError($attribute, Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
351    }
352
353    /**
354     * Checks if the given value is empty.
355     * A value is considered empty if it is null, an empty array, or an empty string.
356     * Note that this method is different from PHP empty(). It will return false when the value is 0.
357     * @param mixed $value the value to be checked
358     * @return boolean whether the value is empty
359     */
360    public function isEmpty($value)
361    {
362        if ($this->isEmpty !== null) {
363            return call_user_func($this->isEmpty, $value);
364        } else {
365            return $value === null || $value === [] || $value === '';
366        }
367    }
368}