PageRenderTime 29ms CodeModel.GetById 19ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/yiisoft/yii2/validators/Validator.php

https://gitlab.com/hostingvk4/hostingvk4
PHP | 366 lines | 136 code | 18 blank | 212 comment | 22 complexity | 993ce6eb3de96cea047dcf9887a5b014 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 * - `email`: [[EmailValidator]]
 31 * - `exist`: [[ExistValidator]]
 32 * - `file`: [[FileValidator]]
 33 * - `filter`: [[FilterValidator]]
 34 * - `image`: [[ImageValidator]]
 35 * - `in`: [[RangeValidator]]
 36 * - `integer`: [[NumberValidator]]
 37 * - `match`: [[RegularExpressionValidator]]
 38 * - `required`: [[RequiredValidator]]
 39 * - `safe`: [[SafeValidator]]
 40 * - `string`: [[StringValidator]]
 41 * - `trim`: [[FilterValidator]]
 42 * - `unique`: [[UniqueValidator]]
 43 * - `url`: [[UrlValidator]]
 44 *
 45 * @author Qiang Xue <qiang.xue@gmail.com>
 46 * @since 2.0
 47 */
 48class Validator extends Component
 49{
 50    /**
 51     * @var array list of built-in validators (name => class or configuration)
 52     */
 53    public static $builtInValidators = [
 54        'boolean' => 'yii\validators\BooleanValidator',
 55        'captcha' => 'yii\captcha\CaptchaValidator',
 56        'compare' => 'yii\validators\CompareValidator',
 57        'date' => 'yii\validators\DateValidator',
 58        'default' => 'yii\validators\DefaultValueValidator',
 59        'double' => 'yii\validators\NumberValidator',
 60        'email' => 'yii\validators\EmailValidator',
 61        'exist' => 'yii\validators\ExistValidator',
 62        'file' => 'yii\validators\FileValidator',
 63        'filter' => 'yii\validators\FilterValidator',
 64        'image' => 'yii\validators\ImageValidator',
 65        'in' => 'yii\validators\RangeValidator',
 66        'integer' => [
 67            'class' => 'yii\validators\NumberValidator',
 68            'integerOnly' => true,
 69        ],
 70        'match' => 'yii\validators\RegularExpressionValidator',
 71        'number' => 'yii\validators\NumberValidator',
 72        'required' => 'yii\validators\RequiredValidator',
 73        'safe' => 'yii\validators\SafeValidator',
 74        'string' => 'yii\validators\StringValidator',
 75        'trim' => [
 76            'class' => 'yii\validators\FilterValidator',
 77            'filter' => 'trim',
 78            'skipOnArray' => true,
 79        ],
 80        'unique' => 'yii\validators\UniqueValidator',
 81        'url' => 'yii\validators\UrlValidator',
 82    ];
 83    /**
 84     * @var array|string attributes to be validated by this validator. For multiple attributes,
 85     * please specify them as an array; for single attribute, you may use either a string or an array.
 86     */
 87    public $attributes = [];
 88    /**
 89     * @var string the user-defined error message. It may contain the following placeholders which
 90     * will be replaced accordingly by the validator:
 91     *
 92     * - `{attribute}`: the label of the attribute being validated
 93     * - `{value}`: the value of the attribute being validated
 94     *
 95     * Note that some validators may introduce other properties for error messages used when specific
 96     * validation conditions are not met. Please refer to individual class API documentation for details
 97     * about these properties. By convention, this property represents the primary error message
 98     * used when the most important validation condition is not met.
 99     */
100    public $message;
101    /**
102     * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
103     * please specify them as an array; for single scenario, you may use either a string or an array.
104     */
105    public $on = [];
106    /**
107     * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
108     * please specify them as an array; for single scenario, you may use either a string or an array.
109     */
110    public $except = [];
111    /**
112     * @var boolean whether this validation rule should be skipped if the attribute being validated
113     * already has some validation error according to some previous rules. Defaults to true.
114     */
115    public $skipOnError = true;
116    /**
117     * @var boolean whether this validation rule should be skipped if the attribute value
118     * is null or an empty string.
119     */
120    public $skipOnEmpty = true;
121    /**
122     * @var boolean whether to enable client-side validation for this validator.
123     * The actual client-side validation is done via the JavaScript code returned
124     * by [[clientValidateAttribute()]]. If that method returns null, even if this property
125     * is true, no client-side validation will be done by this validator.
126     */
127    public $enableClientValidation = true;
128    /**
129     * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
130     * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
131     * of the callable should be `function ($value)` which returns a boolean indicating
132     * whether the value is empty.
133     */
134    public $isEmpty;
135    /**
136     * @var callable a PHP callable whose return value determines whether this validator should be applied.
137     * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
138     * refer to the model and the attribute currently being validated. The callable should return a boolean value.
139     *
140     * This property is mainly provided to support conditional validation on the server side.
141     * If this property is not set, this validator will be always applied on the server side.
142     *
143     * The following example will enable the validator only when the country currently selected is USA:
144     *
145     * ```php
146     * function ($model) {
147     *     return $model->country == Country::USA;
148     * }
149     * ```
150     *
151     * @see whenClient
152     */
153    public $when;
154    /**
155     * @var string a JavaScript function name whose return value determines whether this validator should be applied
156     * on the client side. The signature of the function should be `function (attribute, value)`, where
157     * `attribute` is the name of the attribute being validated and `value` the current value of the attribute.
158     *
159     * This property is mainly provided to support conditional validation on the client side.
160     * If this property is not set, this validator will be always applied on the client side.
161     *
162     * The following example will enable the validator only when the country currently selected is USA:
163     *
164     * ```php
165     * function (attribute, value) {
166     *     return $('#country').value == 'USA';
167     * }
168     * ```
169     *
170     * @see when
171     */
172    public $whenClient;
173
174
175    /**
176     * Creates a validator object.
177     * @param mixed $type the validator type. This can be a built-in validator name,
178     * a method name of the model class, an anonymous function, or a validator class name.
179     * @param \yii\base\Model $model the data model to be validated.
180     * @param array|string $attributes list of attributes to be validated. This can be either an array of
181     * the attribute names or a string of comma-separated attribute names.
182     * @param array $params initial values to be applied to the validator properties
183     * @return Validator the validator
184     */
185    public static function createValidator($type, $model, $attributes, $params = [])
186    {
187        $params['attributes'] = $attributes;
188
189        if ($type instanceof \Closure || $model->hasMethod($type)) {
190            // method-based validator
191            $params['class'] = __NAMESPACE__ . '\InlineValidator';
192            $params['method'] = $type;
193        } else {
194            if (isset(static::$builtInValidators[$type])) {
195                $type = static::$builtInValidators[$type];
196            }
197            if (is_array($type)) {
198                $params = array_merge($type, $params);
199            } else {
200                $params['class'] = $type;
201            }
202        }
203
204        return Yii::createObject($params);
205    }
206
207    /**
208     * @inheritdoc
209     */
210    public function init()
211    {
212        parent::init();
213        $this->attributes = (array) $this->attributes;
214        $this->on = (array) $this->on;
215        $this->except = (array) $this->except;
216    }
217
218    /**
219     * Validates the specified object.
220     * @param \yii\base\Model $model the data model being validated
221     * @param array|null $attributes the list of attributes to be validated.
222     * Note that if an attribute is not associated with the validator,
223     * it will be ignored.
224     * If this parameter is null, every attribute listed in [[attributes]] will be validated.
225     */
226    public function validateAttributes($model, $attributes = null)
227    {
228        if (is_array($attributes)) {
229            $attributes = array_intersect($this->attributes, $attributes);
230        } else {
231            $attributes = $this->attributes;
232        }
233        foreach ($attributes as $attribute) {
234            $skip = $this->skipOnError && $model->hasErrors($attribute)
235                || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
236            if (!$skip) {
237                if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
238                    $this->validateAttribute($model, $attribute);
239                }
240            }
241        }
242    }
243
244    /**
245     * Validates a single attribute.
246     * Child classes must implement this method to provide the actual validation logic.
247     * @param \yii\base\Model $model the data model to be validated
248     * @param string $attribute the name of the attribute to be validated.
249     */
250    public function validateAttribute($model, $attribute)
251    {
252        $result = $this->validateValue($model->$attribute);
253        if (!empty($result)) {
254            $this->addError($model, $attribute, $result[0], $result[1]);
255        }
256    }
257
258    /**
259     * Validates a given value.
260     * You may use this method to validate a value out of the context of a data model.
261     * @param mixed $value the data value to be validated.
262     * @param string $error the error message to be returned, if the validation fails.
263     * @return boolean whether the data is valid.
264     */
265    public function validate($value, &$error = null)
266    {
267        $result = $this->validateValue($value);
268        if (empty($result)) {
269            return true;
270        }
271
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     * Validates a value.
282     * A validator class can implement this method to support data validation out of the context of a data model.
283     * @param mixed $value the data value to be validated.
284     * @return array|null the error message and the parameters to be inserted into the error message.
285     * Null should be returned if the data is valid.
286     * @throws NotSupportedException if the validator does not supporting data validation without a model
287     */
288    protected function validateValue($value)
289    {
290        throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
291    }
292
293    /**
294     * Returns the JavaScript needed for performing client-side validation.
295     *
296     * You may override this method to return the JavaScript validation code if
297     * the validator can support client-side validation.
298     *
299     * The following JavaScript variables are predefined and can be used in the validation code:
300     *
301     * - `attribute`: the name of the attribute being validated.
302     * - `value`: the value being validated.
303     * - `messages`: an array used to hold the validation error messages for the attribute.
304     * - `deferred`: an array used to hold deferred objects for asynchronous validation
305     *
306     * @param \yii\base\Model $model the data model 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($model, $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 $model the data model 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($model, $attribute, $message, $params = [])
344    {
345        $value = $model->$attribute;
346        $params['attribute'] = $model->getAttributeLabel($attribute);
347        $params['value'] = is_array($value) ? 'array()' : $value;
348        $model->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}