PageRenderTime 199ms CodeModel.GetById 25ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/htdocs/yii/framework/validators/CValidator.php

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