Validator.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.2.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Validation;
  16. use Cake\Validation\RulesProvider;
  17. use Cake\Validation\ValidationSet;
  18. /**
  19. * Validator object encapsulates all methods related to data validations for a model
  20. * It also provides an API to dynamically change validation rules for each model field.
  21. *
  22. * Implements ArrayAccess to easily modify rules in the set
  23. *
  24. * @link http://book.cakephp.org/2.0/en/data-validation.html
  25. */
  26. class Validator implements \ArrayAccess, \IteratorAggregate, \Countable {
  27. /**
  28. * Holds the ValidationSet objects array
  29. *
  30. * @var array
  31. */
  32. protected $_fields = [];
  33. /**
  34. * An associative array of objects or classes containing methods
  35. * used for validation
  36. *
  37. * @var array
  38. */
  39. protected $_providers = [];
  40. /**
  41. * The translation domain to use when setting the error messages
  42. *
  43. * @var string
  44. */
  45. protected $_validationDomain = 'default';
  46. /**
  47. * Contains the validation messages associated with checking the presence
  48. * for each corresponding field.
  49. *
  50. * @var array
  51. */
  52. protected $_presenceMessages = [];
  53. /**
  54. * Contains the validation messages associated with checking the emptiness
  55. * for each corresponding field.
  56. *
  57. * @var array
  58. */
  59. protected $_allowEmptyMessages = [];
  60. /**
  61. * Returns an array of fields that have failed validation. On the current model. This method will
  62. * actually run validation rules over data, not just return the messages.
  63. *
  64. * @param array $data The data to be checked for errors
  65. * @param boolean $newRecord whether the data to be validated is new or to be updated.
  66. * @return array Array of invalid fields
  67. * @see Validator::validates()
  68. */
  69. public function errors(array $data, $newRecord = true) {
  70. $errors = [];
  71. $requiredMessage = __d('cake', 'This field is required');
  72. $emptyMessage = __d('cake', 'This field cannot be left empty');
  73. foreach ($this->_fields as $name => $field) {
  74. $keyPresent = array_key_exists($name, $data);
  75. if (!$keyPresent && !$this->_checkPresence($field, $newRecord)) {
  76. $errors[$name][] = isset($this->_presenceMessages[$name])
  77. ? __d($this->_validationDomain, $this->_presenceMessages[$name])
  78. : $requiredMessage;
  79. continue;
  80. }
  81. if (!$keyPresent) {
  82. continue;
  83. }
  84. $canBeEmpty = $this->_canBeEmpty($field, $newRecord);
  85. $isEmpty = $this->_fieldIsEmpty($data[$name]);
  86. if (!$canBeEmpty && $isEmpty) {
  87. $errors[$name][] = isset($this->_allowEmptyMessages[$name])
  88. ? __d($this->_validationDomain, $this->_allowEmptyMessages[$name])
  89. : $emptyMessage;
  90. continue;
  91. }
  92. if ($isEmpty) {
  93. continue;
  94. }
  95. $result = $this->_processRules($field, $data[$name], $data, $newRecord);
  96. if ($result) {
  97. $errors[$name] = $result;
  98. }
  99. }
  100. return $errors;
  101. }
  102. /**
  103. * Returns a ValidationSet object containing all validation rules for a field, if
  104. * passed a ValidationSet as second argument, it will replace any other rule set defined
  105. * before
  106. *
  107. * @param string $name [optional] The fieldname to fetch.
  108. * @param \Cake\Validation\ValidationSet $set The set of rules for field
  109. * @return \Cake\Validation\ValidationSet
  110. */
  111. public function field($name, ValidationSet $set = null) {
  112. if (empty($this->_fields[$name])) {
  113. $set = $set ?: new ValidationSet;
  114. $this->_fields[$name] = $set;
  115. }
  116. return $this->_fields[$name];
  117. }
  118. /**
  119. * Check whether or not a validator contains any rules for the given field.
  120. *
  121. * @param string $name The field name to check.
  122. * @return boolean
  123. */
  124. public function hasField($name) {
  125. return isset($this->_fields[$name]);
  126. }
  127. /**
  128. * Associates an object to a name so it can be used as a provider. Providers are
  129. * objects or class names that can contain methods used during validation of for
  130. * deciding whether a validation rule can be applied. All validation methods,
  131. * when called will receive the full list of providers stored in this validator.
  132. *
  133. * If called with no arguments, it will return the provider stored under that name if
  134. * it exists, otherwise it returns this instance of chaining.
  135. *
  136. * @param string $name
  137. * @param null|object|string $object
  138. * @return Validator|object|string
  139. */
  140. public function provider($name, $object = null) {
  141. if ($object === null) {
  142. if (isset($this->_providers[$name])) {
  143. return $this->_providers[$name];
  144. }
  145. if ($name === 'default') {
  146. return $this->_providers[$name] = new RulesProvider;
  147. }
  148. return null;
  149. }
  150. $this->_providers[$name] = $object;
  151. return $this;
  152. }
  153. /**
  154. * Sets the I18n domain for validation messages. This method is chainable.
  155. *
  156. * @param string $validationDomain The validation domain to be used.
  157. * @return \Cake\Validation\Validation
  158. */
  159. public function setValidationDomain($validationDomain) {
  160. $this->_validationDomain = $validationDomain;
  161. return $this;
  162. }
  163. /**
  164. * Returns whether a rule set is defined for a field or not
  165. *
  166. * @param string $field name of the field to check
  167. * @return boolean
  168. */
  169. public function offsetExists($field) {
  170. return isset($this->_fields[$field]);
  171. }
  172. /**
  173. * Returns the rule set for a field
  174. *
  175. * @param string $field name of the field to check
  176. * @return \Cake\Validation\ValidationSet
  177. */
  178. public function offsetGet($field) {
  179. return $this->field($field);
  180. }
  181. /**
  182. * Sets the rule set for a field
  183. *
  184. * @param string $field name of the field to set
  185. * @param array|\Cake\Validation\ValidationSet $rules set of rules to apply to field
  186. * @return void
  187. */
  188. public function offsetSet($field, $rules) {
  189. if (!$rules instanceof ValidationSet) {
  190. $set = new ValidationSet;
  191. foreach ((array)$rules as $name => $rule) {
  192. $set->add($name, $rule);
  193. }
  194. }
  195. $this->_fields[$field] = $rules;
  196. }
  197. /**
  198. * Unsets the rule set for a field
  199. *
  200. * @param string $field name of the field to unset
  201. * @return void
  202. */
  203. public function offsetUnset($field) {
  204. unset($this->_fields[$field]);
  205. }
  206. /**
  207. * Returns an iterator for each of the fields to be validated
  208. *
  209. * @return \ArrayIterator
  210. */
  211. public function getIterator() {
  212. return new \ArrayIterator($this->_fields);
  213. }
  214. /**
  215. * Returns the number of fields having validation rules
  216. *
  217. * @return integer
  218. */
  219. public function count() {
  220. return count($this->_fields);
  221. }
  222. /**
  223. * Adds a new rule to a field's rule set. If second argument is an array
  224. * then rules list for the field will be replaced with second argument and
  225. * third argument will be ignored.
  226. *
  227. * ## Example:
  228. *
  229. * {{{
  230. * $validator
  231. * ->add('title', 'required', array('rule' => 'notEmpty'))
  232. * ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
  233. *
  234. * $validator->add('password', array(
  235. * 'size' => array('rule' => array('between', 8, 20)),
  236. * 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
  237. * ));
  238. * }}}
  239. *
  240. * @param string $field The name of the field from wich the rule will be removed
  241. * @param array|string $name The alias for a single rule or multiple rules array
  242. * @param array|\Cake\Validation\ValidationRule $rule the rule to add
  243. * @return Validator this instance
  244. */
  245. public function add($field, $name, $rule = []) {
  246. $field = $this->field($field);
  247. if (!is_array($name)) {
  248. $rules = [$name => $rule];
  249. } else {
  250. $rules = $name;
  251. }
  252. foreach ($rules as $name => $rule) {
  253. $field->add($name, $rule);
  254. }
  255. return $this;
  256. }
  257. /**
  258. * Removes a rule from the set by its name
  259. *
  260. * ## Example:
  261. *
  262. * {{{
  263. * $validator
  264. * ->remove('title', 'required')
  265. * ->remove('user_id')
  266. * }}}
  267. *
  268. * @param string $field The name of the field from which the rule will be removed
  269. * @param string $rule the name of the rule to be removed
  270. * @return Validator this instance
  271. */
  272. public function remove($field, $rule = null) {
  273. if ($rule === null) {
  274. unset($this->_fields[$field]);
  275. } else {
  276. $this->field($field)->remove($rule);
  277. }
  278. return $this;
  279. }
  280. /**
  281. * Sets whether a field is required to be present in data array.
  282. *
  283. * @param string $field the name of the field
  284. * @param boolean|string $mode Valid values are true, false, 'create', 'update'
  285. * @param string $message The validation message to show if the field presence
  286. * is required.
  287. * @return Validator this instance
  288. */
  289. public function validatePresence($field, $mode = true, $message = null) {
  290. $this->field($field)->isPresenceRequired($mode);
  291. if ($message) {
  292. $this->_presenceMessages[$field] = $message;
  293. }
  294. return $this;
  295. }
  296. /**
  297. * Sets whether a field is allowed to be empty. If it is, all other validation
  298. * rules will be ignored
  299. *
  300. * @param string $field the name of the field
  301. * @param boolean|string $mode Valid values are true, false, 'create', 'update'
  302. * @param string $message The validation message to show if the field is not
  303. * allowed to be empty.
  304. * @return Validator this instance
  305. */
  306. public function allowEmpty($field, $mode = true, $message = null) {
  307. $this->field($field)->isEmptyAllowed($mode);
  308. if ($message) {
  309. $this->_allowEmptyMessages[$field] = $message;
  310. }
  311. return $this;
  312. }
  313. /**
  314. * Returns whether or not a field can be left empty for a new or already existing
  315. * record.
  316. *
  317. * @param string $field
  318. * @param boolean $newRecord whether the data to be validated is new or to be updated.
  319. * @return boolean
  320. */
  321. public function isEmptyAllowed($field, $newRecord) {
  322. return $this->_canBeEmpty($this->field($field), $newRecord);
  323. }
  324. /**
  325. * Returns whether or not a field can be left out for a new or already existing
  326. * record.
  327. *
  328. * @param string $field
  329. * @param boolean $newRecord whether the data to be validated is new or to be updated.
  330. * @return boolean
  331. */
  332. public function isPresenceRequired($field, $newRecord) {
  333. return !$this->_checkPresence($this->field($field), $newRecord);
  334. }
  335. /**
  336. * Returns false if any validation for the passed rule set should be stopped
  337. * due to the field missing in the data array
  338. *
  339. * @param ValidationSet $field the set of rules for a field
  340. * @param boolean $newRecord whether the data to be validated is new or to be updated.
  341. * @return boolean
  342. */
  343. protected function _checkPresence($field, $newRecord) {
  344. $required = $field->isPresenceRequired();
  345. if (in_array($required, ['create', 'update'], true)) {
  346. return (
  347. ($required === 'create' && !$newRecord) ||
  348. ($required === 'update' && $newRecord)
  349. );
  350. }
  351. return !$required;
  352. }
  353. /**
  354. * Returns whether the field can be left blank according to `allowEmpty`
  355. *
  356. * @param ValidationSet $field the set of rules for a field
  357. * @param boolean $newRecord whether the data to be validated is new or to be updated.
  358. * @return boolean
  359. */
  360. protected function _canBeEmpty($field, $newRecord) {
  361. $allowed = $field->isEmptyAllowed();
  362. if (in_array($allowed, array('create', 'update'), true)) {
  363. $allowed = (
  364. ($allowed === 'create' && $newRecord) ||
  365. ($allowed === 'update' && !$newRecord)
  366. );
  367. }
  368. return $allowed;
  369. }
  370. /**
  371. * Returns true if the field is empty in the passed data array
  372. *
  373. * @param mixed $data value to check against
  374. * @return boolean
  375. */
  376. protected function _fieldIsEmpty($data) {
  377. if (empty($data) && $data !== '0' && $data !== false && $data !== 0) {
  378. return true;
  379. }
  380. return false;
  381. }
  382. /**
  383. * Iterates over each rule in the validation set and collects the errors resulting
  384. * from executing them
  385. *
  386. * @param ValidationSet $rules the list of rules for a field
  387. * @param mixed $value The value to be checked
  388. * @param array $data the full data passed to the validator
  389. * @param boolean $newRecord whether is it a new record or an existing one
  390. * @return array
  391. */
  392. protected function _processRules(ValidationSet $rules, $value, $data, $newRecord) {
  393. $errors = [];
  394. // Loading default provider in case there is none
  395. $this->provider('default');
  396. foreach ($rules as $name => $rule) {
  397. $result = $rule->process($value, $this->_providers, compact('newRecord', 'data'));
  398. if ($result === true) {
  399. continue;
  400. }
  401. $errors[$name] = __d('cake', 'The provided value is invalid');
  402. if (is_string($result)) {
  403. $errors[$name] = __d($this->_validationDomain, $result);
  404. }
  405. if ($rule->isLast()) {
  406. break;
  407. }
  408. }
  409. return $errors;
  410. }
  411. }