PageRenderTime 58ms CodeModel.GetById 30ms 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
Possible License(s): GPL-3.0, BSD-3-Clause, CC0-1.0, BSD-2-Clause, GPL-2.0, LGPL-2.1, LGPL-3.0
  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. * CValidator is the base class for all validators.
  12. *
  13. * Child classes must implement the {@link validateAttribute} method.
  14. *
  15. * The following properties are defined in CValidator:
  16. * <ul>
  17. * <li>{@link attributes}: array, list of attributes to be validated;</li>
  18. * <li>{@link message}: string, the customized error message. The message
  19. * may contain placeholders that will be replaced with the actual content.
  20. * For example, the "{attribute}" placeholder will be replaced with the label
  21. * of the problematic attribute. Different validators may define additional
  22. * placeholders.</li>
  23. * <li>{@link on}: string, in which scenario should the validator be in effect.
  24. * This is used to match the 'on' parameter supplied when calling {@link CModel::validate}.</li>
  25. * </ul>
  26. *
  27. * When using {@link createValidator} to create a validator, the following aliases
  28. * are recognized as the corresponding built-in validator classes:
  29. * <ul>
  30. * <li>required: {@link CRequiredValidator}</li>
  31. * <li>filter: {@link CFilterValidator}</li>
  32. * <li>match: {@link CRegularExpressionValidator}</li>
  33. * <li>email: {@link CEmailValidator}</li>
  34. * <li>url: {@link CUrlValidator}</li>
  35. * <li>unique: {@link CUniqueValidator}</li>
  36. * <li>compare: {@link CCompareValidator}</li>
  37. * <li>length: {@link CStringValidator}</li>
  38. * <li>in: {@link CRangeValidator}</li>
  39. * <li>numerical: {@link CNumberValidator}</li>
  40. * <li>captcha: {@link CCaptchaValidator}</li>
  41. * <li>type: {@link CTypeValidator}</li>
  42. * <li>file: {@link CFileValidator}</li>
  43. * <li>default: {@link CDefaultValueValidator}</li>
  44. * <li>exist: {@link CExistValidator}</li>
  45. * <li>boolean: {@link CBooleanValidator}</li>
  46. * <li>date: {@link CDateValidator}</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 3160 2011-04-03 01:08:23Z qiang.xue $
  53. * @package system.validators
  54. * @since 1.0
  55. */
  56. abstract 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. 'date'=>'CDateValidator',
  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. * @var boolean whether to perform client-side validation. Defaults to true.
  111. * Please refer to {@link CActiveForm::enableClientValidation} for more details about client-side validation.
  112. * @since 1.1.7
  113. */
  114. public $enableClientValidation=true;
  115. /**
  116. * Validates a single attribute.
  117. * This method should be overridden by child classes.
  118. * @param CModel $object the data object being validated
  119. * @param string $attribute the name of the attribute to be validated.
  120. */
  121. abstract protected function validateAttribute($object,$attribute);
  122. /**
  123. * Creates a validator object.
  124. * @param string $name the name or class of the validator
  125. * @param CModel $object the data object being validated that may contain the inline validation method
  126. * @param mixed $attributes list of attributes to be validated. This can be either an array of
  127. * the attribute names or a string of comma-separated attribute names.
  128. * @param array $params initial values to be applied to the validator properties
  129. * @return CValidator the validator
  130. */
  131. public static function createValidator($name,$object,$attributes,$params=array())
  132. {
  133. if(is_string($attributes))
  134. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  135. if(isset($params['on']))
  136. {
  137. if(is_array($params['on']))
  138. $on=$params['on'];
  139. else
  140. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  141. }
  142. else
  143. $on=array();
  144. if(method_exists($object,$name))
  145. {
  146. $validator=new CInlineValidator;
  147. $validator->attributes=$attributes;
  148. $validator->method=$name;
  149. $validator->params=$params;
  150. if(isset($params['skipOnError']))
  151. $validator->skipOnError=$params['skipOnError'];
  152. }
  153. else
  154. {
  155. $params['attributes']=$attributes;
  156. if(isset(self::$builtInValidators[$name]))
  157. $className=Yii::import(self::$builtInValidators[$name],true);
  158. else
  159. $className=Yii::import($name,true);
  160. $validator=new $className;
  161. foreach($params as $name=>$value)
  162. $validator->$name=$value;
  163. }
  164. $validator->on=empty($on) ? array() : array_combine($on,$on);
  165. return $validator;
  166. }
  167. /**
  168. * Validates the specified object.
  169. * @param CModel $object the data object being validated
  170. * @param array $attributes the list of attributes to be validated. Defaults to null,
  171. * meaning every attribute listed in {@link 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. foreach($attributes as $attribute)
  180. {
  181. if(!$this->skipOnError || !$object->hasErrors($attribute))
  182. $this->validateAttribute($object,$attribute);
  183. }
  184. }
  185. /**
  186. * Returns the JavaScript needed for performing client-side validation.
  187. * Do not override this method if the validator does not support client-side validation.
  188. * Two predefined JavaScript variables can be used:
  189. * <ul>
  190. * <li>value: the value to be validated</li>
  191. * <li>messages: an array used to hold the validation error messages for the value</li>
  192. * </ul>
  193. * @param CModel $object the data object being validated
  194. * @param string $attribute the name of the attribute to be validated.
  195. * @return string the client-side validation script. Null if the validator does not support client-side validation.
  196. * @see CActiveForm::enableClientValidation
  197. * @since 1.1.7
  198. */
  199. public function clientValidateAttribute($object,$attribute)
  200. {
  201. }
  202. /**
  203. * Returns a value indicating whether the validator applies to the specified scenario.
  204. * A validator applies to a scenario as long as any of the following conditions is met:
  205. * <ul>
  206. * <li>the validator's "on" property is empty</li>
  207. * <li>the validator's "on" property contains the specified scenario</li>
  208. * </ul>
  209. * @param string $scenario scenario name
  210. * @return boolean whether the validator applies to the specified scenario.
  211. * @since 1.0.2
  212. */
  213. public function applyTo($scenario)
  214. {
  215. return empty($this->on) || isset($this->on[$scenario]);
  216. }
  217. /**
  218. * Adds an error about the specified attribute to the active record.
  219. * This is a helper method that performs message selection and internationalization.
  220. * @param CModel $object the data object being validated
  221. * @param string $attribute the attribute being validated
  222. * @param string $message the error message
  223. * @param array $params values for the placeholders in the error message
  224. */
  225. protected function addError($object,$attribute,$message,$params=array())
  226. {
  227. $params['{attribute}']=$object->getAttributeLabel($attribute);
  228. $object->addError($attribute,strtr($message,$params));
  229. }
  230. /**
  231. * Checks if the given value is empty.
  232. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  233. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  234. * @param mixed $value the value to be checked
  235. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  236. * @return boolean whether the value is empty
  237. * @since 1.0.9
  238. */
  239. protected function isEmpty($value,$trim=false)
  240. {
  241. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  242. }
  243. }