PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/framework/validators/CValidator.php

https://code.google.com/p/monkeys-job/
PHP | 232 lines | 91 code | 14 blank | 127 comment | 15 complexity | cb890221e04582529129489bf001d8da MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, 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>safe: {@link CSafeValidator}</li>
  47. * <li>unsafe: {@link CUnsafeValidator}</li>
  48. * </ul>
  49. *
  50. * @author Qiang Xue <qiang.xue@gmail.com>
  51. * @version $Id: CValidator.php 2799 2011-01-01 19:31:13Z qiang.xue $
  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. );
  80. /**
  81. * @var array list of attributes to be validated.
  82. */
  83. public $attributes;
  84. /**
  85. * @var string the user-defined error message. Different validators may define various
  86. * placeholders in the message that are to be replaced with actual values. All validators
  87. * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
  88. */
  89. public $message;
  90. /**
  91. * @var boolean whether this validation rule should be skipped if when there is already a validation
  92. * error for the current attribute. Defaults to false.
  93. * @since 1.1.1
  94. */
  95. public $skipOnError=false;
  96. /**
  97. * @var array list of scenarios that the validator should be applied.
  98. * Each array value refers to a scenario name with the same name as its array key.
  99. */
  100. public $on;
  101. /**
  102. * @var boolean whether attributes listed with this validator should be considered safe for massive assignment.
  103. * Defaults to true.
  104. * @since 1.1.4
  105. */
  106. public $safe=true;
  107. /**
  108. * Validates a single attribute.
  109. * This method should be overriden by child classes.
  110. * @param CModel $object the data object being validated
  111. * @param string $attribute the name of the attribute to be validated.
  112. */
  113. abstract protected function validateAttribute($object,$attribute);
  114. /**
  115. * Creates a validator object.
  116. * @param string $name the name or class of the validator
  117. * @param CModel $object the data object being validated that may contain the inline validation method
  118. * @param mixed $attributes list of attributes to be validated. This can be either an array of
  119. * the attribute names or a string of comma-separated attribute names.
  120. * @param array $params initial values to be applied to the validator properties
  121. * @return CValidator the validator
  122. */
  123. public static function createValidator($name,$object,$attributes,$params=array())
  124. {
  125. if(is_string($attributes))
  126. $attributes=preg_split('/[\s,]+/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  127. if(isset($params['on']))
  128. {
  129. if(is_array($params['on']))
  130. $on=$params['on'];
  131. else
  132. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  133. }
  134. else
  135. $on=array();
  136. if(method_exists($object,$name))
  137. {
  138. $validator=new CInlineValidator;
  139. $validator->attributes=$attributes;
  140. $validator->method=$name;
  141. $validator->params=$params;
  142. if(isset($params['skipOnError']))
  143. $validator->skipOnError=$params['skipOnError'];
  144. }
  145. else
  146. {
  147. $params['attributes']=$attributes;
  148. if(isset(self::$builtInValidators[$name]))
  149. $className=Yii::import(self::$builtInValidators[$name],true);
  150. else
  151. $className=Yii::import($name,true);
  152. $validator=new $className;
  153. foreach($params as $name=>$value)
  154. $validator->$name=$value;
  155. }
  156. $validator->on=empty($on) ? array() : array_combine($on,$on);
  157. return $validator;
  158. }
  159. /**
  160. * Validates the specified object.
  161. * @param CModel $object the data object being validated
  162. * @param array $attributes the list of attributes to be validated. Defaults to null,
  163. * meaning every attribute listed in {@link attributes} will be validated.
  164. */
  165. public function validate($object,$attributes=null)
  166. {
  167. if(is_array($attributes))
  168. $attributes=array_intersect($this->attributes,$attributes);
  169. else
  170. $attributes=$this->attributes;
  171. foreach($attributes as $attribute)
  172. {
  173. if(!$this->skipOnError || !$object->hasErrors($attribute))
  174. $this->validateAttribute($object,$attribute);
  175. }
  176. }
  177. /**
  178. * Returns a value indicating whether the validator applies to the specified scenario.
  179. * A validator applies to a scenario as long as any of the following conditions is met:
  180. * <ul>
  181. * <li>the validator's "on" property is empty</li>
  182. * <li>the validator's "on" property contains the specified scenario</li>
  183. * </ul>
  184. * @param string $scenario scenario name
  185. * @return boolean whether the validator applies to the specified scenario.
  186. * @since 1.0.2
  187. */
  188. public function applyTo($scenario)
  189. {
  190. return empty($this->on) || isset($this->on[$scenario]);
  191. }
  192. /**
  193. * Adds an error about the specified attribute to the active record.
  194. * This is a helper method that performs message selection and internationalization.
  195. * @param CModel $object the data object being validated
  196. * @param string $attribute the attribute being validated
  197. * @param string $message the error message
  198. * @param array $params values for the placeholders in the error message
  199. */
  200. protected function addError($object,$attribute,$message,$params=array())
  201. {
  202. $params['{attribute}']=$object->getAttributeLabel($attribute);
  203. $object->addError($attribute,strtr($message,$params));
  204. }
  205. /**
  206. * Checks if the given value is empty.
  207. * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
  208. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  209. * @param mixed $value the value to be checked
  210. * @param boolean $trim whether to perform trimming before checking if the string is empty. Defaults to false.
  211. * @return boolean whether the value is empty
  212. * @since 1.0.9
  213. */
  214. protected function isEmpty($value,$trim=false)
  215. {
  216. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  217. }
  218. }