PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/validators/CValidator.php

https://bitbucket.org/darkllangle/zurmo
PHP | 280 lines | 114 code | 16 blank | 150 comment | 19 complexity | fb1835c066b9cce393b6f227e4df4505 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-3.0, LGPL-2.1, BSD-2-Clause
  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$
  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 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 array list of scenarios that the validator should not be applied to.
  105. * Each array value refers to a scenario name with the same name as its array key.
  106. * @since 1.1.11
  107. */
  108. public $except;
  109. /**
  110. * @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
  111. * Defaults to true.
  112. * @since 1.1.4
  113. */
  114. public $safe=true;
  115. /**
  116. * @var boolean whether to perform client-side validation. Defaults to true.
  117. * Please refer to {@link CActiveForm::enableClientValidation} for more details about client-side validation.
  118. * @since 1.1.7
  119. */
  120. public $enableClientValidation=true;
  121. /**
  122. * Validates a single attribute.
  123. * This method should be overridden by child classes.
  124. * @param CModel $object the data object being validated
  125. * @param string $attribute the name of the attribute to be validated.
  126. */
  127. abstract protected function validateAttribute($object,$attribute);
  128. /**
  129. * Creates a validator object.
  130. * @param string $name the name or class of the validator
  131. * @param CModel $object the data object being validated that may contain the inline validation method
  132. * @param mixed $attributes list of attributes to be validated. This can be either an array of
  133. * the attribute names or a string of comma-separated attribute names.
  134. * @param array $params initial values to be applied to the validator properties
  135. * @return CValidator the validator
  136. */
  137. public static function createValidator($name,$object,$attributes,$params=array())
  138. {
  139. if(is_string($attributes))
  140. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  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. if(isset($params['except']))
  151. {
  152. if(is_array($params['except']))
  153. $except=$params['except'];
  154. else
  155. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  156. }
  157. else
  158. $except=array();
  159. if(method_exists($object,$name))
  160. {
  161. $validator=new CInlineValidator;
  162. $validator->attributes=$attributes;
  163. $validator->method=$name;
  164. if(isset($params['clientValidate']))
  165. {
  166. $validator->clientValidate=$params['clientValidate'];
  167. unset($params['clientValidate']);
  168. }
  169. $validator->params=$params;
  170. if(isset($params['skipOnError']))
  171. $validator->skipOnError=$params['skipOnError'];
  172. }
  173. else
  174. {
  175. $params['attributes']=$attributes;
  176. if(isset(self::$builtInValidators[$name]))
  177. $className=Yii::import(self::$builtInValidators[$name],true);
  178. else
  179. $className=Yii::import($name,true);
  180. $validator=new $className;
  181. foreach($params as $name=>$value)
  182. $validator->$name=$value;
  183. }
  184. $validator->on=empty($on) ? array() : array_combine($on,$on);
  185. $validator->except=empty($except) ? array() : array_combine($except,$except);
  186. return $validator;
  187. }
  188. /**
  189. * Validates the specified object.
  190. * @param CModel $object the data object being validated
  191. * @param array $attributes the list of attributes to be validated. Defaults to null,
  192. * meaning every attribute listed in {@link attributes} will be validated.
  193. */
  194. public function validate($object,$attributes=null)
  195. {
  196. if(is_array($attributes))
  197. $attributes=array_intersect($this->attributes,$attributes);
  198. else
  199. $attributes=$this->attributes;
  200. foreach($attributes as $attribute)
  201. {
  202. if(!$this->skipOnError || !$object->hasErrors($attribute))
  203. $this->validateAttribute($object,$attribute);
  204. }
  205. }
  206. /**
  207. * Returns the JavaScript needed for performing client-side validation.
  208. * Do not override this method if the validator does not support client-side validation.
  209. * Two predefined JavaScript variables can be used:
  210. * <ul>
  211. * <li>value: the value to be validated</li>
  212. * <li>messages: an array used to hold the validation error messages for the value</li>
  213. * </ul>
  214. * @param CModel $object the data object being validated
  215. * @param string $attribute the name of the attribute to be validated.
  216. * @return string the client-side validation script. Null if the validator does not support client-side validation.
  217. * @see CActiveForm::enableClientValidation
  218. * @since 1.1.7
  219. */
  220. public function clientValidateAttribute($object,$attribute)
  221. {
  222. }
  223. /**
  224. * Returns a value indicating whether the validator applies to the specified scenario.
  225. * A validator applies to a scenario as long as any of the following conditions is met:
  226. * <ul>
  227. * <li>the validator's "on" property is empty</li>
  228. * <li>the validator's "on" property contains the specified scenario</li>
  229. * </ul>
  230. * @param string $scenario scenario name
  231. * @return boolean whether the validator applies to the specified scenario.
  232. */
  233. public function applyTo($scenario)
  234. {
  235. if(isset($this->except[$scenario]))
  236. return false;
  237. return empty($this->on) || isset($this->on[$scenario]);
  238. }
  239. /**
  240. * Adds an error about the specified attribute to the active record.
  241. * This is a helper method that performs message selection and internationalization.
  242. * @param CModel $object the data object being validated
  243. * @param string $attribute the attribute being validated
  244. * @param string $message the error message
  245. * @param array $params values for the placeholders in the error message
  246. */
  247. protected function addError($object,$attribute,$message,$params=array())
  248. {
  249. $params['{attribute}']=$object->getAttributeLabel($attribute);
  250. $object->addError($attribute,strtr($message,$params));
  251. }
  252. /**
  253. * Checks if the given value is empty.
  254. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  255. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  256. * @param mixed $value the value to be checked
  257. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  258. * @return boolean whether the value is empty
  259. */
  260. protected function isEmpty($value,$trim=false)
  261. {
  262. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  263. }
  264. }