PageRenderTime 58ms CodeModel.GetById 24ms app.highlight 26ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/validators/Validator.php

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