PageRenderTime 13ms CodeModel.GetById 1ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/yii/validators/Validator.php

https://github.com/stefan321/yii2
PHP | 270 lines | 107 code | 16 blank | 147 comment | 23 complexity | 851d4423f2e630052e03ec5d664f940d 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 [[validateAttribute()]] method 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`: [[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 * - `in`: [[RangeValidator]]
 35 * - `integer`: [[NumberValidator]]
 36 * - `match`: [[RegularExpressionValidator]]
 37 * - `required`: [[RequiredValidator]]
 38 * - `string`: [[StringValidator]]
 39 * - `unique`: [[UniqueValidator]]
 40 * - `url`: [[UrlValidator]]
 41 *
 42 * @author Qiang Xue <qiang.xue@gmail.com>
 43 * @since 2.0
 44 */
 45abstract class Validator extends Component
 46{
 47	/**
 48	 * @var array list of built-in validators (name => class or configuration)
 49	 */
 50	public static $builtInValidators = array(
 51		'boolean' => 'yii\validators\BooleanValidator',
 52		'captcha' => 'yii\validators\CaptchaValidator',
 53		'compare' => 'yii\validators\CompareValidator',
 54		'date' => 'yii\validators\DateValidator',
 55		'default' => 'yii\validators\DefaultValueValidator',
 56		'double' => 'yii\validators\NumberValidator',
 57		'email' => 'yii\validators\EmailValidator',
 58		'exist' => 'yii\validators\ExistValidator',
 59		'file' => 'yii\validators\FileValidator',
 60		'filter' => 'yii\validators\FilterValidator',
 61		'in' => 'yii\validators\RangeValidator',
 62		'integer' => array(
 63			'class' => 'yii\validators\NumberValidator',
 64			'integerOnly' => true,
 65		),
 66		'match' => 'yii\validators\RegularExpressionValidator',
 67		'number' => 'yii\validators\NumberValidator',
 68		'required' => 'yii\validators\RequiredValidator',
 69		'string' => 'yii\validators\StringValidator',
 70		'unique' => 'yii\validators\UniqueValidator',
 71		'url' => 'yii\validators\UrlValidator',
 72	);
 73
 74	/**
 75	 * @var array list of attributes to be validated.
 76	 */
 77	public $attributes;
 78	/**
 79	 * @var string the user-defined error message. It may contain the following placeholders which
 80	 * will be replaced accordingly by the validator:
 81	 *
 82	 * - `{attribute}`: the label of the attribute being validated
 83	 * - `{value}`: the value of the attribute being validated
 84	 */
 85	public $message;
 86	/**
 87	 * @var array list of scenarios that the validator can be applied to.
 88	 */
 89	public $on = array();
 90	/**
 91	 * @var array list of scenarios that the validator should not be applied to.
 92	 */
 93	public $except = array();
 94	/**
 95	 * @var boolean whether this validation rule should be skipped if the attribute being validated
 96	 * already has some validation error according to some previous rules. Defaults to true.
 97	 */
 98	public $skipOnError = true;
 99	/**
100	 * @var boolean whether this validation rule should be skipped if the attribute value
101	 * is null or an empty string.
102	 */
103	public $skipOnEmpty = true;
104	/**
105	 * @var boolean whether to enable client-side validation for this validator.
106	 * The actual client-side validation is done via the JavaScript code returned
107	 * by [[clientValidateAttribute()]]. If that method returns null, even if this property
108	 * is true, no client-side validation will be done by this validator.
109	 */
110	public $enableClientValidation = true;
111
112	/**
113	 * Validates a single attribute.
114	 * Child classes must implement this method to provide the actual validation logic.
115	 * @param \yii\base\Model $object the data object to be validated
116	 * @param string $attribute the name of the attribute to be validated.
117	 */
118	abstract public function validateAttribute($object, $attribute);
119
120	/**
121	 * Creates a validator object.
122	 * @param string $type the validator type. This can be a method name,
123	 * a built-in validator name, a class name, or a path alias of the validator class.
124	 * @param \yii\base\Model $object the data object to be validated.
125	 * @param array|string $attributes list of attributes to be validated. This can be either an array of
126	 * the attribute names or a string of comma-separated attribute names.
127	 * @param array $params initial values to be applied to the validator properties
128	 * @return Validator the validator
129	 */
130	public static function createValidator($type, $object, $attributes, $params = array())
131	{
132		if (!is_array($attributes)) {
133			$attributes = preg_split('/[\s,]+/', $attributes, -1, PREG_SPLIT_NO_EMPTY);
134		}
135		$params['attributes'] = $attributes;
136
137		if (isset($params['on']) && !is_array($params['on'])) {
138			$params['on'] = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
139		}
140
141		if (isset($params['except']) && !is_array($params['except'])) {
142			$params['except'] = preg_split('/[\s,]+/', $params['except'], -1, PREG_SPLIT_NO_EMPTY);
143		}
144
145		if (method_exists($object, $type)) {
146			// method-based validator
147			$params['class'] = __NAMESPACE__ . '\InlineValidator';
148			$params['method'] = $type;
149		} else {
150			if (isset(self::$builtInValidators[$type])) {
151				$type = self::$builtInValidators[$type];
152			}
153			if (is_array($type)) {
154				foreach ($type as $name => $value) {
155					$params[$name] = $value;
156				}
157			} else {
158				$params['class'] = $type;
159			}
160		}
161
162		return Yii::createObject($params);
163	}
164
165	/**
166	 * Validates the specified object.
167	 * @param \yii\base\Model $object the data object being validated
168	 * @param array|null $attributes the list of attributes to be validated.
169	 * Note that if an attribute is not associated with the validator,
170	 * it will be ignored.
171	 * If this parameter is null, every attribute listed in [[attributes]] will be validated.
172	 */
173	public function validate($object, $attributes = null)
174	{
175		if (is_array($attributes)) {
176			$attributes = array_intersect($this->attributes, $attributes);
177		} else {
178			$attributes = $this->attributes;
179		}
180		foreach ($attributes as $attribute) {
181			$skip = $this->skipOnError && $object->hasErrors($attribute)
182				 || $this->skipOnEmpty && $this->isEmpty($object->$attribute);
183			if (!$skip) {
184				$this->validateAttribute($object, $attribute);
185			}
186		}
187	}
188
189	/**
190	 * Validates a value.
191	 * A validator class can implement this method to support data validation out of the context of a data model.
192	 * @param mixed $value the data value to be validated.
193	 * @throws NotSupportedException if data validation without a model is not supported
194	 */
195	public function validateValue($value)
196	{
197		throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
198	}
199
200	/**
201	 * Returns the JavaScript needed for performing client-side validation.
202	 *
203	 * You may override this method to return the JavaScript validation code if
204	 * the validator can support client-side validation.
205	 *
206	 * The following JavaScript variables are predefined and can be used in the validation code:
207	 *
208	 * - `attribute`: the name of the attribute being validated.
209	 * - `value`: the value being validated.
210	 * - `messages`: an array used to hold the validation error messages for the attribute.
211	 *
212	 * @param \yii\base\Model $object the data object being validated
213	 * @param string $attribute the name of the attribute to be validated.
214	 * @param \yii\base\View $view the view object that is going to be used to render views or view files
215	 * containing a model form with this validator applied.
216	 * @return string the client-side validation script. Null if the validator does not support
217	 * client-side validation.
218	 * @see \yii\web\ActiveForm::enableClientValidation
219	 */
220	public function clientValidateAttribute($object, $attribute, $view)
221	{
222		return null;
223	}
224
225	/**
226	 * Returns a value indicating whether the validator is active for the given scenario and attribute.
227	 *
228	 * A validator is active if
229	 *
230	 * - the validator's `on` property is empty, or
231	 * - the validator's `on` property contains the specified scenario
232	 *
233	 * @param string $scenario scenario name
234	 * @return boolean whether the validator applies to the specified scenario.
235	 */
236	public function isActive($scenario)
237	{
238		return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
239	}
240
241	/**
242	 * Adds an error about the specified attribute to the model object.
243	 * This is a helper method that performs message selection and internationalization.
244	 * @param \yii\base\Model $object the data object being validated
245	 * @param string $attribute the attribute being validated
246	 * @param string $message the error message
247	 * @param array $params values for the placeholders in the error message
248	 */
249	public function addError($object, $attribute, $message, $params = array())
250	{
251		$value = $object->$attribute;
252		$params['{attribute}'] = $object->getAttributeLabel($attribute);
253		$params['{value}'] = is_array($value) ? 'array()' : $value;
254		$object->addError($attribute, strtr($message, $params));
255	}
256
257	/**
258	 * Checks if the given value is empty.
259	 * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
260	 * Note that this method is different from PHP empty(). It will return false when the value is 0.
261	 * @param mixed $value the value to be checked
262	 * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
263	 * @return boolean whether the value is empty
264	 */
265	public function isEmpty($value, $trim = false)
266	{
267		return $value === null || $value === array() || $value === ''
268			|| $trim && is_scalar($value) && trim($value) === '';
269	}
270}