PageRenderTime 28ms CodeModel.GetById 21ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/validators/CValidator.php

https://bitbucket.org/dinhtrung/yiicorecms/
PHP | 258 lines | 96 code | 15 blank | 147 comment | 15 complexity | 315ed6124db173f0fd11d3e74480c047 MD5 | raw file
  1<?php
  2/**
  3 * CValidator class file.
  4 *
  5 * @author Qiang Xue <qiang.xue@gmail.com>
  6 * @link http://www.yiiframework.com/
  7 * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8 * @license http://www.yiiframework.com/license/
  9 */
 10
 11/**
 12 * CValidator is the base class for all validators.
 13 *
 14 * Child classes must implement the {@link validateAttribute} method.
 15 *
 16 * The following properties are defined in CValidator:
 17 * <ul>
 18 * <li>{@link attributes}: array, list of attributes to be validated;</li>
 19 * <li>{@link message}: string, the customized error message. The message
 20 *   may contain placeholders that will be replaced with the actual content.
 21 *   For example, the "{attribute}" placeholder will be replaced with the label
 22 *   of the problematic attribute. Different validators may define additional
 23 *   placeholders.</li>
 24 * <li>{@link on}: string, in which scenario should the validator be in effect.
 25 *   This is used to match the 'on' parameter supplied when calling {@link CModel::validate}.</li>
 26 * </ul>
 27 *
 28 * When using {@link createValidator} to create a validator, the following aliases
 29 * are recognized as the corresponding built-in validator classes:
 30 * <ul>
 31 * <li>required: {@link CRequiredValidator}</li>
 32 * <li>filter: {@link CFilterValidator}</li>
 33 * <li>match: {@link CRegularExpressionValidator}</li>
 34 * <li>email: {@link CEmailValidator}</li>
 35 * <li>url: {@link CUrlValidator}</li>
 36 * <li>unique: {@link CUniqueValidator}</li>
 37 * <li>compare: {@link CCompareValidator}</li>
 38 * <li>length: {@link CStringValidator}</li>
 39 * <li>in: {@link CRangeValidator}</li>
 40 * <li>numerical: {@link CNumberValidator}</li>
 41 * <li>captcha: {@link CCaptchaValidator}</li>
 42 * <li>type: {@link CTypeValidator}</li>
 43 * <li>file: {@link CFileValidator}</li>
 44 * <li>default: {@link CDefaultValueValidator}</li>
 45 * <li>exist: {@link CExistValidator}</li>
 46 * <li>boolean: {@link CBooleanValidator}</li>
 47 * <li>date: {@link CDateValidator}</li>
 48 * <li>safe: {@link CSafeValidator}</li>
 49 * <li>unsafe: {@link CUnsafeValidator}</li>
 50 * </ul>
 51 *
 52 * @author Qiang Xue <qiang.xue@gmail.com>
 53 * @version $Id: CValidator.php 3160 2011-04-03 01:08:23Z qiang.xue $
 54 * @package system.validators
 55 * @since 1.0
 56 */
 57abstract class CValidator extends CComponent
 58{
 59	/**
 60	 * @var array list of built-in validators (name=>class)
 61	 */
 62	public static $builtInValidators=array(
 63		'required'=>'CRequiredValidator',
 64		'filter'=>'CFilterValidator',
 65		'match'=>'CRegularExpressionValidator',
 66		'email'=>'CEmailValidator',
 67		'url'=>'CUrlValidator',
 68		'unique'=>'CUniqueValidator',
 69		'compare'=>'CCompareValidator',
 70		'length'=>'CStringValidator',
 71		'in'=>'CRangeValidator',
 72		'numerical'=>'CNumberValidator',
 73		'captcha'=>'CCaptchaValidator',
 74		'type'=>'CTypeValidator',
 75		'file'=>'CFileValidator',
 76		'default'=>'CDefaultValueValidator',
 77		'exist'=>'CExistValidator',
 78		'boolean'=>'CBooleanValidator',
 79		'safe'=>'CSafeValidator',
 80		'unsafe'=>'CUnsafeValidator',
 81		'date'=>'CDateValidator',
 82	);
 83
 84	/**
 85	 * @var array list of attributes to be validated.
 86	 */
 87	public $attributes;
 88	/**
 89	 * @var string the user-defined error message. Different validators may define various
 90	 * placeholders in the message that are to be replaced with actual values. All validators
 91	 * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
 92	 */
 93	public $message;
 94	/**
 95	 * @var boolean whether this validation rule should be skipped if when there is already a validation
 96	 * error for the current attribute. Defaults to false.
 97	 * @since 1.1.1
 98	 */
 99	public $skipOnError=false;
100	/**
101	 * @var array list of scenarios that the validator should be applied.
102	 * Each array value refers to a scenario name with the same name as its array key.
103	 */
104	public $on;
105	/**
106	 * @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
107	 * Defaults to true.
108	 * @since 1.1.4
109	 */
110	public $safe=true;
111	/**
112	 * @var boolean whether to perform client-side validation. Defaults to true.
113	 * Please refer to {@link CActiveForm::enableClientValidation} for more details about client-side validation.
114	 * @since 1.1.7
115	 */
116	public $enableClientValidation=true;
117
118	/**
119	 * Validates a single attribute.
120	 * This method should be overridden by child classes.
121	 * @param CModel $object the data object being validated
122	 * @param string $attribute the name of the attribute to be validated.
123	 */
124	abstract protected function validateAttribute($object,$attribute);
125
126
127	/**
128	 * Creates a validator object.
129	 * @param string $name the name or class of the validator
130	 * @param CModel $object the data object being validated that may contain the inline validation method
131	 * @param mixed $attributes list of attributes to be validated. This can be either an array of
132	 * the attribute names or a string of comma-separated attribute names.
133	 * @param array $params initial values to be applied to the validator properties
134	 * @return CValidator the validator
135	 */
136	public static function createValidator($name,$object,$attributes,$params=array())
137	{
138		if(is_string($attributes))
139			$attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
140
141		if(isset($params['on']))
142		{
143			if(is_array($params['on']))
144				$on=$params['on'];
145			else
146				$on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
147		}
148		else
149			$on=array();
150
151		if(method_exists($object,$name))
152		{
153			$validator=new CInlineValidator;
154			$validator->attributes=$attributes;
155			$validator->method=$name;
156			$validator->params=$params;
157			if(isset($params['skipOnError']))
158				$validator->skipOnError=$params['skipOnError'];
159		}
160		else
161		{
162			$params['attributes']=$attributes;
163			if(isset(self::$builtInValidators[$name]))
164				$className=Yii::import(self::$builtInValidators[$name],true);
165			else
166				$className=Yii::import($name,true);
167			$validator=new $className;
168			foreach($params as $name=>$value)
169				$validator->$name=$value;
170		}
171
172		$validator->on=empty($on) ? array() : array_combine($on,$on);
173
174		return $validator;
175	}
176
177	/**
178	 * Validates the specified object.
179	 * @param CModel $object the data object being validated
180	 * @param array $attributes the list of attributes to be validated. Defaults to null,
181	 * meaning every attribute listed in {@link attributes} will be validated.
182	 */
183	public function validate($object,$attributes=null)
184	{
185		if(is_array($attributes))
186			$attributes=array_intersect($this->attributes,$attributes);
187		else
188			$attributes=$this->attributes;
189		foreach($attributes as $attribute)
190		{
191			if(!$this->skipOnError || !$object->hasErrors($attribute))
192				$this->validateAttribute($object,$attribute);
193		}
194	}
195
196	/**
197	 * Returns the JavaScript needed for performing client-side validation.
198	 * Do not override this method if the validator does not support client-side validation.
199	 * Two predefined JavaScript variables can be used:
200	 * <ul>
201	 * <li>value: the value to be validated</li>
202	 * <li>messages: an array used to hold the validation error messages for the value</li>
203	 * </ul>
204	 * @param CModel $object the data object being validated
205	 * @param string $attribute the name of the attribute to be validated.
206	 * @return string the client-side validation script. Null if the validator does not support client-side validation.
207	 * @see CActiveForm::enableClientValidation
208	 * @since 1.1.7
209	 */
210	public function clientValidateAttribute($object,$attribute)
211	{
212	}
213
214	/**
215	 * Returns a value indicating whether the validator applies to the specified scenario.
216	 * A validator applies to a scenario as long as any of the following conditions is met:
217	 * <ul>
218	 * <li>the validator's "on" property is empty</li>
219	 * <li>the validator's "on" property contains the specified scenario</li>
220	 * </ul>
221	 * @param string $scenario scenario name
222	 * @return boolean whether the validator applies to the specified scenario.
223	 * @since 1.0.2
224	 */
225	public function applyTo($scenario)
226	{
227		return empty($this->on) || isset($this->on[$scenario]);
228	}
229
230	/**
231	 * Adds an error about the specified attribute to the active record.
232	 * This is a helper method that performs message selection and internationalization.
233	 * @param CModel $object the data object being validated
234	 * @param string $attribute the attribute being validated
235	 * @param string $message the error message
236	 * @param array $params values for the placeholders in the error message
237	 */
238	protected function addError($object,$attribute,$message,$params=array())
239	{
240		$params['{attribute}']=$object->getAttributeLabel($attribute);
241		$object->addError($attribute,strtr($message,$params));
242	}
243
244	/**
245	 * Checks if the given value is empty.
246	 * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
247	 * Note that this method is different from PHP empty(). It will return false when the value is 0.
248	 * @param mixed $value the value to be checked
249	 * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
250	 * @return boolean whether the value is empty
251	 * @since 1.0.9
252	 */
253	protected function isEmpty($value,$trim=false)
254	{
255		return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
256	}
257}
258