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

/yii/framework/validators/CValidator.php

https://github.com/ashie1287/headfirst
PHP | 232 lines | 91 code | 14 blank | 127 comment | 15 complexity | 17d008ebdf7c8974b30013398f84af2a 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-2010 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>safe: {@link CSafeValidator}</li>
 48 * <li>unsafe: {@link CUnsafeValidator}</li>
 49 * </ul>
 50 *
 51 * @author Qiang Xue <qiang.xue@gmail.com>
 52 * @version $Id: CValidator.php 2268 2010-07-18 17:44:48Z qiang.xue $
 53 * @package system.validators
 54 * @since 1.0
 55 */
 56abstract class CValidator extends CComponent
 57{
 58	/**
 59	 * @var array list of built-in validators (name=>class)
 60	 */
 61	public static $builtInValidators=array(
 62		'required'=>'CRequiredValidator',
 63		'filter'=>'CFilterValidator',
 64		'match'=>'CRegularExpressionValidator',
 65		'email'=>'CEmailValidator',
 66		'url'=>'CUrlValidator',
 67		'unique'=>'CUniqueValidator',
 68		'compare'=>'CCompareValidator',
 69		'length'=>'CStringValidator',
 70		'in'=>'CRangeValidator',
 71		'numerical'=>'CNumberValidator',
 72		'captcha'=>'CCaptchaValidator',
 73		'type'=>'CTypeValidator',
 74		'file'=>'CFileValidator',
 75		'default'=>'CDefaultValueValidator',
 76		'exist'=>'CExistValidator',
 77		'boolean'=>'CBooleanValidator',
 78		'safe'=>'CSafeValidator',
 79		'unsafe'=>'CUnsafeValidator',
 80	);
 81
 82	/**
 83	 * @var array list of attributes to be validated.
 84	 */
 85	public $attributes;
 86	/**
 87	 * @var string the user-defined error message. Different validators may define various
 88	 * placeholders in the message that are to be replaced with actual values. All validators
 89	 * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
 90	 */
 91	public $message;
 92	/**
 93	 * @var boolean whether this validation rule should be skipped if when there is already a validation
 94	 * error for the current attribute. Defaults to false.
 95	 * @since 1.1.1
 96	 */
 97	public $skipOnError=false;
 98	/**
 99	 * @var array list of scenarios that the validator should be applied.
100	 * Each array value refers to a scenario name with the same name as its array key.
101	 */
102	public $on;
103	/**
104	 * @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
105	 * Defaults to true.
106	 * @since 1.1.4
107	 */
108	public $safe=true;
109
110	/**
111	 * Validates a single attribute.
112	 * This method should be overriden by child classes.
113	 * @param CModel the data object being validated
114	 * @param string the name of the attribute to be validated.
115	 */
116	abstract protected function validateAttribute($object,$attribute);
117
118
119	/**
120	 * Creates a validator object.
121	 * @param string the name or class of the validator
122	 * @param CModel the data object being validated that may contain the inline validation method
123	 * @param mixed list of attributes to be validated. This can be either an array of
124	 * the attribute names or a string of comma-separated attribute names.
125	 * @param array initial values to be applied to the validator properties
126	 * @return CValidator the validator
127	 */
128	public static function createValidator($name,$object,$attributes,$params)
129	{
130		if(is_string($attributes))
131			$attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
132
133		if(isset($params['on']))
134		{
135			if(is_array($params['on']))
136				$on=$params['on'];
137			else
138				$on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
139		}
140		else
141			$on=array();
142
143		if(method_exists($object,$name))
144		{
145			$validator=new CInlineValidator;
146			$validator->attributes=$attributes;
147			$validator->method=$name;
148			$validator->params=$params;
149			if(isset($params['skipOnError']))
150				$validator->skipOnError=$params['skipOnError'];
151		}
152		else
153		{
154			$params['attributes']=$attributes;
155			if(isset(self::$builtInValidators[$name]))
156				$className=Yii::import(self::$builtInValidators[$name],true);
157			else
158				$className=Yii::import($name,true);
159			$validator=new $className;
160			foreach($params as $name=>$value)
161				$validator->$name=$value;
162		}
163
164		$validator->on=empty($on) ? array() : array_combine($on,$on);
165
166		return $validator;
167	}
168
169	/**
170	 * Validates the specified object.
171	 * @param CModel the data object being validated
172	 * @param array the list of attributes to be validated. Defaults to null,
173	 * meaning every attribute listed in {@link attributes} will be validated.
174	 */
175	public function validate($object,$attributes=null)
176	{
177		if(is_array($attributes))
178			$attributes=array_intersect($this->attributes,$attributes);
179		else
180			$attributes=$this->attributes;
181		foreach($attributes as $attribute)
182		{
183			if(!$this->skipOnError || !$object->hasErrors($attribute))
184				$this->validateAttribute($object,$attribute);
185		}
186	}
187
188	/**
189	 * Returns a value indicating whether the validator applies to the specified scenario.
190	 * A validator applies to a scenario as long as any of the following conditions is met:
191	 * <ul>
192	 * <li>the validator's "on" property is empty</li>
193	 * <li>the validator's "on" property contains the specified scenario</li>
194	 * </ul>
195	 * @param string scenario name
196	 * @return boolean whether the validator applies to the specified scenario.
197	 * @since 1.0.2
198	 */
199	public function applyTo($scenario)
200	{
201		return empty($this->on) || isset($this->on[$scenario]);
202	}
203
204	/**
205	 * Adds an error about the specified attribute to the active record.
206	 * This is a helper method that performs message selection and internationalization.
207	 * @param CModel the data object being validated
208	 * @param string the attribute being validated
209	 * @param string the error message
210	 * @param array values for the placeholders in the error message
211	 */
212	protected function addError($object,$attribute,$message,$params=array())
213	{
214		$params['{attribute}']=$object->getAttributeLabel($attribute);
215		$object->addError($attribute,strtr($message,$params));
216	}
217
218	/**
219	 * Checks if the given value is empty.
220	 * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
221	 * Note that this method is different from PHP empty(). It will return false when the value is 0.
222	 * @param mixed the value to be checked
223	 * @param boolean whether to perform trimming before checking if the string is empty. Defaults to false.
224	 * @return boolean whether the value is empty
225	 * @since 1.0.9
226	 */
227	protected function isEmpty($value,$trim=false)
228	{
229		return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
230	}
231}
232