PageRenderTime 45ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/validators/CValidator.php

https://bitbucket.org/kwangchin/zurmo
PHP | 279 lines | 114 code | 16 blank | 149 comment | 19 complexity | 66a7c09a167334cb283849ad008ed6ee MD5 | raw file
Possible License(s): LGPL-2.1, BSD-2-Clause, GPL-2.0, GPL-3.0, BSD-3-Clause, 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. * @package system.validators
  53. * @since 1.0
  54. */
  55. abstract class CValidator extends CComponent
  56. {
  57. /**
  58. * @var array list of built-in validators (name=>class)
  59. */
  60. public static $builtInValidators=array(
  61. 'required'=>'CRequiredValidator',
  62. 'filter'=>'CFilterValidator',
  63. 'match'=>'CRegularExpressionValidator',
  64. 'email'=>'CEmailValidator',
  65. 'url'=>'CUrlValidator',
  66. 'unique'=>'CUniqueValidator',
  67. 'compare'=>'CCompareValidator',
  68. 'length'=>'CStringValidator',
  69. 'in'=>'CRangeValidator',
  70. 'numerical'=>'CNumberValidator',
  71. 'captcha'=>'CCaptchaValidator',
  72. 'type'=>'CTypeValidator',
  73. 'file'=>'CFileValidator',
  74. 'default'=>'CDefaultValueValidator',
  75. 'exist'=>'CExistValidator',
  76. 'boolean'=>'CBooleanValidator',
  77. 'safe'=>'CSafeValidator',
  78. 'unsafe'=>'CUnsafeValidator',
  79. 'date'=>'CDateValidator',
  80. );
  81. /**
  82. * @var array list of attributes to be validated.
  83. */
  84. public $attributes;
  85. /**
  86. * @var string the user-defined error message. Different validators may define various
  87. * placeholders in the message that are to be replaced with actual values. All validators
  88. * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
  89. */
  90. public $message;
  91. /**
  92. * @var boolean whether this validation rule should be skipped when there is already a validation
  93. * error for the current attribute. Defaults to false.
  94. * @since 1.1.1
  95. */
  96. public $skipOnError=false;
  97. /**
  98. * @var array list of scenarios that the validator should be applied.
  99. * Each array value refers to a scenario name with the same name as its array key.
  100. */
  101. public $on;
  102. /**
  103. * @var array list of scenarios that the validator should not be applied to.
  104. * Each array value refers to a scenario name with the same name as its array key.
  105. * @since 1.1.11
  106. */
  107. public $except;
  108. /**
  109. * @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
  110. * Defaults to true.
  111. * @since 1.1.4
  112. */
  113. public $safe=true;
  114. /**
  115. * @var boolean whether to perform client-side validation. Defaults to true.
  116. * Please refer to {@link CActiveForm::enableClientValidation} for more details about client-side validation.
  117. * @since 1.1.7
  118. */
  119. public $enableClientValidation=true;
  120. /**
  121. * Validates a single attribute.
  122. * This method should be overridden by child classes.
  123. * @param CModel $object the data object being validated
  124. * @param string $attribute the name of the attribute to be validated.
  125. */
  126. abstract protected function validateAttribute($object,$attribute);
  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. if(isset($params['on']))
  141. {
  142. if(is_array($params['on']))
  143. $on=$params['on'];
  144. else
  145. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  146. }
  147. else
  148. $on=array();
  149. if(isset($params['except']))
  150. {
  151. if(is_array($params['except']))
  152. $except=$params['except'];
  153. else
  154. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  155. }
  156. else
  157. $except=array();
  158. if(method_exists($object,$name))
  159. {
  160. $validator=new CInlineValidator;
  161. $validator->attributes=$attributes;
  162. $validator->method=$name;
  163. if(isset($params['clientValidate']))
  164. {
  165. $validator->clientValidate=$params['clientValidate'];
  166. unset($params['clientValidate']);
  167. }
  168. $validator->params=$params;
  169. if(isset($params['skipOnError']))
  170. $validator->skipOnError=$params['skipOnError'];
  171. }
  172. else
  173. {
  174. $params['attributes']=$attributes;
  175. if(isset(self::$builtInValidators[$name]))
  176. $className=Yii::import(self::$builtInValidators[$name],true);
  177. else
  178. $className=Yii::import($name,true);
  179. $validator=new $className;
  180. foreach($params as $name=>$value)
  181. $validator->$name=$value;
  182. }
  183. $validator->on=empty($on) ? array() : array_combine($on,$on);
  184. $validator->except=empty($except) ? array() : array_combine($except,$except);
  185. return $validator;
  186. }
  187. /**
  188. * Validates the specified object.
  189. * @param CModel $object the data object being validated
  190. * @param array $attributes the list of attributes to be validated. Defaults to null,
  191. * meaning every attribute listed in {@link attributes} will be validated.
  192. */
  193. public function validate($object,$attributes=null)
  194. {
  195. if(is_array($attributes))
  196. $attributes=array_intersect($this->attributes,$attributes);
  197. else
  198. $attributes=$this->attributes;
  199. foreach($attributes as $attribute)
  200. {
  201. if(!$this->skipOnError || !$object->hasErrors($attribute))
  202. $this->validateAttribute($object,$attribute);
  203. }
  204. }
  205. /**
  206. * Returns the JavaScript needed for performing client-side validation.
  207. * Do not override this method if the validator does not support client-side validation.
  208. * Two predefined JavaScript variables can be used:
  209. * <ul>
  210. * <li>value: the value to be validated</li>
  211. * <li>messages: an array used to hold the validation error messages for the value</li>
  212. * </ul>
  213. * @param CModel $object the data object being validated
  214. * @param string $attribute the name of the attribute to be validated.
  215. * @return string the client-side validation script. Null if the validator does not support client-side validation.
  216. * @see CActiveForm::enableClientValidation
  217. * @since 1.1.7
  218. */
  219. public function clientValidateAttribute($object,$attribute)
  220. {
  221. }
  222. /**
  223. * Returns a value indicating whether the validator applies to the specified scenario.
  224. * A validator applies to a scenario as long as any of the following conditions is met:
  225. * <ul>
  226. * <li>the validator's "on" property is empty</li>
  227. * <li>the validator's "on" property contains the specified scenario</li>
  228. * </ul>
  229. * @param string $scenario scenario name
  230. * @return boolean whether the validator applies to the specified scenario.
  231. */
  232. public function applyTo($scenario)
  233. {
  234. if(isset($this->except[$scenario]))
  235. return false;
  236. return empty($this->on) || isset($this->on[$scenario]);
  237. }
  238. /**
  239. * Adds an error about the specified attribute to the active record.
  240. * This is a helper method that performs message selection and internationalization.
  241. * @param CModel $object the data object being validated
  242. * @param string $attribute the attribute being validated
  243. * @param string $message the error message
  244. * @param array $params values for the placeholders in the error message
  245. */
  246. protected function addError($object,$attribute,$message,$params=array())
  247. {
  248. $params['{attribute}']=$object->getAttributeLabel($attribute);
  249. $object->addError($attribute,strtr($message,$params));
  250. }
  251. /**
  252. * Checks if the given value is empty.
  253. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  254. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  255. * @param mixed $value the value to be checked
  256. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  257. * @return boolean whether the value is empty
  258. */
  259. protected function isEmpty($value,$trim=false)
  260. {
  261. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  262. }
  263. }