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

/vendor/yiisoft/yii2/validators/Validator.php

https://gitlab.com/lcp0578/simpleforum
PHP | 368 lines | 137 code | 18 blank | 213 comment | 22 complexity | 5cd5635216ef1349599e3309f09bff7a MD5 | raw file
Possible License(s): JSON, BSD-3-Clause, MIT
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\NotSupportedException;
  11. /**
  12. * Validator is the base class for all validators.
  13. *
  14. * Child classes should override the [[validateValue()]] and/or [[validateAttribute()]] methods to provide the actual
  15. * logic of performing data validation. Child classes may also override [[clientValidateAttribute()]]
  16. * to provide client-side validation support.
  17. *
  18. * Validator declares a set of [[builtInValidators|built-in validators] which can
  19. * be referenced using short names. They are listed as follows:
  20. *
  21. * - `boolean`: [[BooleanValidator]]
  22. * - `captcha`: [[\yii\captcha\CaptchaValidator]]
  23. * - `compare`: [[CompareValidator]]
  24. * - `date`: [[DateValidator]]
  25. * - `default`: [[DefaultValueValidator]]
  26. * - `double`: [[NumberValidator]]
  27. * - `each`: [[EachValidator]]
  28. * - `email`: [[EmailValidator]]
  29. * - `exist`: [[ExistValidator]]
  30. * - `file`: [[FileValidator]]
  31. * - `filter`: [[FilterValidator]]
  32. * - `image`: [[ImageValidator]]
  33. * - `in`: [[RangeValidator]]
  34. * - `integer`: [[NumberValidator]]
  35. * - `match`: [[RegularExpressionValidator]]
  36. * - `required`: [[RequiredValidator]]
  37. * - `safe`: [[SafeValidator]]
  38. * - `string`: [[StringValidator]]
  39. * - `trim`: [[FilterValidator]]
  40. * - `unique`: [[UniqueValidator]]
  41. * - `url`: [[UrlValidator]]
  42. *
  43. * @author Qiang Xue <qiang.xue@gmail.com>
  44. * @since 2.0
  45. */
  46. class Validator extends Component
  47. {
  48. /**
  49. * @var array list of built-in validators (name => class or configuration)
  50. */
  51. public static $builtInValidators = [
  52. 'boolean' => 'yii\validators\BooleanValidator',
  53. 'captcha' => 'yii\captcha\CaptchaValidator',
  54. 'compare' => 'yii\validators\CompareValidator',
  55. 'date' => 'yii\validators\DateValidator',
  56. 'default' => 'yii\validators\DefaultValueValidator',
  57. 'double' => 'yii\validators\NumberValidator',
  58. 'each' => 'yii\validators\EachValidator',
  59. 'email' => 'yii\validators\EmailValidator',
  60. 'exist' => 'yii\validators\ExistValidator',
  61. 'file' => 'yii\validators\FileValidator',
  62. 'filter' => 'yii\validators\FilterValidator',
  63. 'image' => 'yii\validators\ImageValidator',
  64. 'in' => 'yii\validators\RangeValidator',
  65. 'integer' => [
  66. 'class' => 'yii\validators\NumberValidator',
  67. 'integerOnly' => true,
  68. ],
  69. 'match' => 'yii\validators\RegularExpressionValidator',
  70. 'number' => 'yii\validators\NumberValidator',
  71. 'required' => 'yii\validators\RequiredValidator',
  72. 'safe' => 'yii\validators\SafeValidator',
  73. 'string' => 'yii\validators\StringValidator',
  74. 'trim' => [
  75. 'class' => 'yii\validators\FilterValidator',
  76. 'filter' => 'trim',
  77. 'skipOnArray' => true,
  78. ],
  79. 'unique' => 'yii\validators\UniqueValidator',
  80. 'url' => 'yii\validators\UrlValidator',
  81. ];
  82. /**
  83. * @var array|string attributes to be validated by this validator. For multiple attributes,
  84. * please specify them as an array; for single attribute, you may use either a string or an array.
  85. */
  86. public $attributes = [];
  87. /**
  88. * @var string the user-defined error message. It may contain the following placeholders which
  89. * will be replaced accordingly by the validator:
  90. *
  91. * - `{attribute}`: the label of the attribute being validated
  92. * - `{value}`: the value of the attribute being validated
  93. *
  94. * Note that some validators may introduce other properties for error messages used when specific
  95. * validation conditions are not met. Please refer to individual class API documentation for details
  96. * about these properties. By convention, this property represents the primary error message
  97. * used when the most important validation condition is not met.
  98. */
  99. public $message;
  100. /**
  101. * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
  102. * please specify them as an array; for single scenario, you may use either a string or an array.
  103. */
  104. public $on = [];
  105. /**
  106. * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
  107. * please specify them as an array; for single scenario, you may use either a string or an array.
  108. */
  109. public $except = [];
  110. /**
  111. * @var boolean whether this validation rule should be skipped if the attribute being validated
  112. * already has some validation error according to some previous rules. Defaults to true.
  113. */
  114. public $skipOnError = true;
  115. /**
  116. * @var boolean whether this validation rule should be skipped if the attribute value
  117. * is null or an empty string.
  118. */
  119. public $skipOnEmpty = true;
  120. /**
  121. * @var boolean whether to enable client-side validation for this validator.
  122. * The actual client-side validation is done via the JavaScript code returned
  123. * by [[clientValidateAttribute()]]. If that method returns null, even if this property
  124. * is true, no client-side validation will be done by this validator.
  125. */
  126. public $enableClientValidation = true;
  127. /**
  128. * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
  129. * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
  130. * of the callable should be `function ($value)` which returns a boolean indicating
  131. * whether the value is empty.
  132. */
  133. public $isEmpty;
  134. /**
  135. * @var callable a PHP callable whose return value determines whether this validator should be applied.
  136. * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
  137. * refer to the model and the attribute currently being validated. The callable should return a boolean value.
  138. *
  139. * This property is mainly provided to support conditional validation on the server side.
  140. * If this property is not set, this validator will be always applied on the server side.
  141. *
  142. * The following example will enable the validator only when the country currently selected is USA:
  143. *
  144. * ```php
  145. * function ($model) {
  146. * return $model->country == Country::USA;
  147. * }
  148. * ```
  149. *
  150. * @see whenClient
  151. */
  152. public $when;
  153. /**
  154. * @var string a JavaScript function name whose return value determines whether this validator should be applied
  155. * on the client side. The signature of the function should be `function (attribute, value)`, where
  156. * `attribute` is the name of the attribute being validated and `value` the current value of the attribute.
  157. *
  158. * This property is mainly provided to support conditional validation on the client side.
  159. * If this property is not set, this validator will be always applied on the client side.
  160. *
  161. * The following example will enable the validator only when the country currently selected is USA:
  162. *
  163. * ```php
  164. * function (attribute, value) {
  165. * return $('#country').val() === 'USA';
  166. * }
  167. * ```
  168. *
  169. * @see when
  170. */
  171. public $whenClient;
  172. /**
  173. * Creates a validator object.
  174. * @param mixed $type the validator type. This can be a built-in validator name,
  175. * a method name of the model class, an anonymous function, or a validator class name.
  176. * @param \yii\base\Model $model the data model to be validated.
  177. * @param array|string $attributes list of attributes to be validated. This can be either an array of
  178. * the attribute names or a string of comma-separated attribute names.
  179. * @param array $params initial values to be applied to the validator properties
  180. * @return Validator the validator
  181. */
  182. public static function createValidator($type, $model, $attributes, $params = [])
  183. {
  184. $params['attributes'] = $attributes;
  185. if ($type instanceof \Closure || $model->hasMethod($type)) {
  186. // method-based validator
  187. $params['class'] = __NAMESPACE__ . '\InlineValidator';
  188. $params['method'] = $type;
  189. } else {
  190. if (isset(static::$builtInValidators[$type])) {
  191. $type = static::$builtInValidators[$type];
  192. }
  193. if (is_array($type)) {
  194. $params = array_merge($type, $params);
  195. } else {
  196. $params['class'] = $type;
  197. }
  198. }
  199. return Yii::createObject($params);
  200. }
  201. /**
  202. * @inheritdoc
  203. */
  204. public function init()
  205. {
  206. parent::init();
  207. $this->attributes = (array) $this->attributes;
  208. $this->on = (array) $this->on;
  209. $this->except = (array) $this->except;
  210. }
  211. /**
  212. * Validates the specified object.
  213. * @param \yii\base\Model $model the data model being validated
  214. * @param array|null $attributes the list of attributes to be validated.
  215. * Note that if an attribute is not associated with the validator,
  216. * it will be ignored.
  217. * If this parameter is null, every attribute listed in [[attributes]] will be validated.
  218. */
  219. public function validateAttributes($model, $attributes = null)
  220. {
  221. if (is_array($attributes)) {
  222. $attributes = array_intersect($this->attributes, $attributes);
  223. } else {
  224. $attributes = $this->attributes;
  225. }
  226. foreach ($attributes as $attribute) {
  227. $skip = $this->skipOnError && $model->hasErrors($attribute)
  228. || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
  229. if (!$skip) {
  230. if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
  231. $this->validateAttribute($model, $attribute);
  232. }
  233. }
  234. }
  235. }
  236. /**
  237. * Validates a single attribute.
  238. * Child classes must implement this method to provide the actual validation logic.
  239. * @param \yii\base\Model $model the data model to be validated
  240. * @param string $attribute the name of the attribute to be validated.
  241. */
  242. public function validateAttribute($model, $attribute)
  243. {
  244. $result = $this->validateValue($model->$attribute);
  245. if (!empty($result)) {
  246. $this->addError($model, $attribute, $result[0], $result[1]);
  247. }
  248. }
  249. /**
  250. * Validates a given value.
  251. * You may use this method to validate a value out of the context of a data model.
  252. * @param mixed $value the data value to be validated.
  253. * @param string $error the error message to be returned, if the validation fails.
  254. * @return boolean whether the data is valid.
  255. */
  256. public function validate($value, &$error = null)
  257. {
  258. $result = $this->validateValue($value);
  259. if (empty($result)) {
  260. return true;
  261. }
  262. list($message, $params) = $result;
  263. $params['attribute'] = Yii::t('yii', 'the input value');
  264. $params['value'] = is_array($value) ? 'array()' : $value;
  265. $error = Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
  266. return false;
  267. }
  268. /**
  269. * Validates a value.
  270. * A validator class can implement this method to support data validation out of the context of a data model.
  271. * @param mixed $value the data value to be validated.
  272. * @return array|null the error message and the parameters to be inserted into the error message.
  273. * Null should be returned if the data is valid.
  274. * @throws NotSupportedException if the validator does not supporting data validation without a model
  275. */
  276. protected function validateValue($value)
  277. {
  278. throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
  279. }
  280. /**
  281. * Returns the JavaScript needed for performing client-side validation.
  282. *
  283. * You may override this method to return the JavaScript validation code if
  284. * the validator can support client-side validation.
  285. *
  286. * The following JavaScript variables are predefined and can be used in the validation code:
  287. *
  288. * - `attribute`: the name of the attribute being validated.
  289. * - `value`: the value being validated.
  290. * - `messages`: an array used to hold the validation error messages for the attribute.
  291. * - `deferred`: an array used to hold deferred objects for asynchronous validation
  292. *
  293. * @param \yii\base\Model $model the data model being validated
  294. * @param string $attribute the name of the attribute to be validated.
  295. * @param \yii\web\View $view the view object that is going to be used to render views or view files
  296. * containing a model form with this validator applied.
  297. * @return string the client-side validation script. Null if the validator does not support
  298. * client-side validation.
  299. * @see \yii\widgets\ActiveForm::enableClientValidation
  300. */
  301. public function clientValidateAttribute($model, $attribute, $view)
  302. {
  303. return null;
  304. }
  305. /**
  306. * Returns a value indicating whether the validator is active for the given scenario and attribute.
  307. *
  308. * A validator is active if
  309. *
  310. * - the validator's `on` property is empty, or
  311. * - the validator's `on` property contains the specified scenario
  312. *
  313. * @param string $scenario scenario name
  314. * @return boolean whether the validator applies to the specified scenario.
  315. */
  316. public function isActive($scenario)
  317. {
  318. return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
  319. }
  320. /**
  321. * Adds an error about the specified attribute to the model object.
  322. * This is a helper method that performs message selection and internationalization.
  323. * @param \yii\base\Model $model the data model being validated
  324. * @param string $attribute the attribute being validated
  325. * @param string $message the error message
  326. * @param array $params values for the placeholders in the error message
  327. */
  328. public function addError($model, $attribute, $message, $params = [])
  329. {
  330. $value = $model->$attribute;
  331. $params['attribute'] = $model->getAttributeLabel($attribute);
  332. $params['value'] = is_array($value) ? 'array()' : $value;
  333. $model->addError($attribute, Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
  334. }
  335. /**
  336. * Checks if the given value is empty.
  337. * A value is considered empty if it is null, an empty array, or an empty string.
  338. * Note that this method is different from PHP empty(). It will return false when the value is 0.
  339. * @param mixed $value the value to be checked
  340. * @return boolean whether the value is empty
  341. */
  342. public function isEmpty($value)
  343. {
  344. if ($this->isEmpty !== null) {
  345. return call_user_func($this->isEmpty, $value);
  346. } else {
  347. return $value === null || $value === [] || $value === '';
  348. }
  349. }
  350. }