PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/demo/yii/validators/CValidator.php

https://bitbucket.org/somethingkindawierd/yii-bootstrap
PHP | 261 lines | 101 code | 15 blank | 145 comment | 16 complexity | 90cf67598eee0b1de61cfa5b6e8d0d33 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-2-Clause, Apache-2.0, BSD-3-Clause, GPL-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 3515 2011-12-28 12:29:24Z mdomba $
  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 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. if(isset($params['clientValidate']))
  150. {
  151. $validator->clientValidate=$params['clientValidate'];
  152. unset($params['clientValidate']);
  153. }
  154. $validator->params=$params;
  155. if(isset($params['skipOnError']))
  156. $validator->skipOnError=$params['skipOnError'];
  157. }
  158. else
  159. {
  160. $params['attributes']=$attributes;
  161. if(isset(self::$builtInValidators[$name]))
  162. $className=Yii::import(self::$builtInValidators[$name],true);
  163. else
  164. $className=Yii::import($name,true);
  165. $validator=new $className;
  166. foreach($params as $name=>$value)
  167. $validator->$name=$value;
  168. }
  169. $validator->on=empty($on) ? array() : array_combine($on,$on);
  170. return $validator;
  171. }
  172. /**
  173. * Validates the specified object.
  174. * @param CModel $object the data object being validated
  175. * @param array $attributes the list of attributes to be validated. Defaults to null,
  176. * meaning every attribute listed in {@link attributes} will be validated.
  177. */
  178. public function validate($object,$attributes=null)
  179. {
  180. if(is_array($attributes))
  181. $attributes=array_intersect($this->attributes,$attributes);
  182. else
  183. $attributes=$this->attributes;
  184. foreach($attributes as $attribute)
  185. {
  186. if(!$this->skipOnError || !$object->hasErrors($attribute))
  187. $this->validateAttribute($object,$attribute);
  188. }
  189. }
  190. /**
  191. * Returns the JavaScript needed for performing client-side validation.
  192. * Do not override this method if the validator does not support client-side validation.
  193. * Two predefined JavaScript variables can be used:
  194. * <ul>
  195. * <li>value: the value to be validated</li>
  196. * <li>messages: an array used to hold the validation error messages for the value</li>
  197. * </ul>
  198. * @param CModel $object the data object being validated
  199. * @param string $attribute the name of the attribute to be validated.
  200. * @return string the client-side validation script. Null if the validator does not support client-side validation.
  201. * @see CActiveForm::enableClientValidation
  202. * @since 1.1.7
  203. */
  204. public function clientValidateAttribute($object,$attribute)
  205. {
  206. }
  207. /**
  208. * Returns a value indicating whether the validator applies to the specified scenario.
  209. * A validator applies to a scenario as long as any of the following conditions is met:
  210. * <ul>
  211. * <li>the validator's "on" property is empty</li>
  212. * <li>the validator's "on" property contains the specified scenario</li>
  213. * </ul>
  214. * @param string $scenario scenario name
  215. * @return boolean whether the validator applies to the specified scenario.
  216. */
  217. public function applyTo($scenario)
  218. {
  219. return empty($this->on) || isset($this->on[$scenario]);
  220. }
  221. /**
  222. * Adds an error about the specified attribute to the active record.
  223. * This is a helper method that performs message selection and internationalization.
  224. * @param CModel $object the data object being validated
  225. * @param string $attribute the attribute being validated
  226. * @param string $message the error message
  227. * @param array $params values for the placeholders in the error message
  228. */
  229. protected function addError($object,$attribute,$message,$params=array())
  230. {
  231. $params['{attribute}']=$object->getAttributeLabel($attribute);
  232. $object->addError($attribute,strtr($message,$params));
  233. }
  234. /**
  235. * Checks if the given value is empty.
  236. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  237. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  238. * @param mixed $value the value to be checked
  239. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  240. * @return boolean whether the value is empty
  241. */
  242. protected function isEmpty($value,$trim=false)
  243. {
  244. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  245. }
  246. }