ModelValidator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. <?php
  2. /**
  3. * ModelValidator.
  4. *
  5. * Provides the Model validation logic.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package Cake.Model
  19. * @since CakePHP(tm) v 2.2.0
  20. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  21. */
  22. namespace Cake\Model;
  23. use Cake\Event\Event;
  24. use Cake\Model\Validator\ValidationSet;
  25. use Cake\Utility\Hash;
  26. /**
  27. * ModelValidator object encapsulates all methods related to data validations for a model
  28. * It also provides an API to dynamically change validation rules for each model field.
  29. *
  30. * Implements ArrayAccess to easily modify rules as usually done with `Model::$validate`
  31. * definition array
  32. *
  33. * @package Cake.Model
  34. * @link http://book.cakephp.org/2.0/en/data-validation.html
  35. */
  36. class ModelValidator implements \ArrayAccess, \IteratorAggregate, \Countable {
  37. /**
  38. * Holds the ValidationSet objects array
  39. *
  40. * @var array
  41. */
  42. protected $_fields = array();
  43. /**
  44. * Holds the reference to the model this Validator is attached to
  45. *
  46. * @var Model
  47. */
  48. protected $_model = array();
  49. /**
  50. * The validators $validate property, used for checking whether validation
  51. * rules definition changed in the model and should be refreshed in this class
  52. *
  53. * @var array
  54. */
  55. protected $_validate = array();
  56. /**
  57. * Holds the available custom callback methods, usually taken from model methods
  58. * and behavior methods
  59. *
  60. * @var array
  61. */
  62. protected $_methods = array();
  63. /**
  64. * Holds the available custom callback methods from the model
  65. *
  66. * @var array
  67. */
  68. protected $_modelMethods = array();
  69. /**
  70. * Holds the list of behavior names that were attached when this object was created
  71. *
  72. * @var array
  73. */
  74. protected $_behaviors = array();
  75. /**
  76. * Constructor
  77. *
  78. * @param Model $Model A reference to the Model the Validator is attached to
  79. */
  80. public function __construct(Model $Model) {
  81. $this->_model = $Model;
  82. }
  83. /**
  84. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  85. * that use the 'with' key as well. Since `Model::_saveMulti` is incapable of exiting a save operation.
  86. *
  87. * Will validate the currently set data. Use `Model::set()` or `Model::create()` to set the active data.
  88. *
  89. * @param array $options An optional array of custom options to be made available in the beforeValidate callback
  90. * @return boolean True if there are no errors
  91. */
  92. public function validates($options = array()) {
  93. $errors = $this->errors($options);
  94. if (empty($errors) && $errors !== false) {
  95. $errors = $this->_validateWithModels($options);
  96. }
  97. if (is_array($errors)) {
  98. return count($errors) === 0;
  99. }
  100. return $errors;
  101. }
  102. /**
  103. * Validates a single record, as well as all its directly associated records.
  104. *
  105. * #### Options
  106. *
  107. * - atomic: If true (default), returns boolean. If false returns array.
  108. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  109. * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
  110. *
  111. * Warning: This method could potentially change the passed argument `$data`,
  112. * If you do not want this to happen, make a copy of `$data` before passing it
  113. * to this method
  114. *
  115. * @param array $data Record data to validate. This should be an array indexed by association name.
  116. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  117. * @return array|boolean If atomic: True on success, or false on failure.
  118. * Otherwise: array similar to the $data array passed, but values are set to true/false
  119. * depending on whether each record validated successfully.
  120. */
  121. public function validateAssociated(&$data, $options = array()) {
  122. $model = $this->getModel();
  123. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  124. $model->validationErrors = $validationErrors = $return = array();
  125. $model->create(null);
  126. $return[$model->alias] = true;
  127. if (!($model->set($data) && $model->validates($options))) {
  128. $validationErrors[$model->alias] = $model->validationErrors;
  129. $return[$model->alias] = false;
  130. }
  131. $data = $model->data;
  132. if (!empty($options['deep']) && isset($data[$model->alias])) {
  133. $recordData = $data[$model->alias];
  134. unset($data[$model->alias]);
  135. $data = array_merge($data, $recordData);
  136. }
  137. $associations = $model->getAssociated();
  138. foreach ($data as $association => &$values) {
  139. $validates = true;
  140. if (isset($associations[$association])) {
  141. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  142. if ($options['deep']) {
  143. $validates = $model->{$association}->validateAssociated($values, $options);
  144. } else {
  145. $model->{$association}->create(null);
  146. $validates = $model->{$association}->set($values) && $model->{$association}->validates($options);
  147. $data[$association] = $model->{$association}->data[$model->{$association}->alias];
  148. }
  149. if (is_array($validates)) {
  150. $validates = !in_array(false, Hash::flatten($validates), true);
  151. }
  152. $return[$association] = $validates;
  153. } elseif ($associations[$association] === 'hasMany') {
  154. $validates = $model->{$association}->validateMany($values, $options);
  155. $return[$association] = $validates;
  156. }
  157. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  158. $validationErrors[$association] = $model->{$association}->validationErrors;
  159. }
  160. }
  161. }
  162. $model->validationErrors = $validationErrors;
  163. if (isset($validationErrors[$model->alias])) {
  164. $model->validationErrors = $validationErrors[$model->alias];
  165. unset($validationErrors[$model->alias]);
  166. $model->validationErrors = array_merge($model->validationErrors, $validationErrors);
  167. }
  168. if (!$options['atomic']) {
  169. return $return;
  170. }
  171. if ($return[$model->alias] === false || !empty($model->validationErrors)) {
  172. return false;
  173. }
  174. return true;
  175. }
  176. /**
  177. * Validates multiple individual records for a single model
  178. *
  179. * #### Options
  180. *
  181. * - atomic: If true (default), returns boolean. If false returns array.
  182. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  183. * - deep: If set to true, all associated data will be validated as well.
  184. *
  185. * Warning: This method could potentially change the passed argument `$data`,
  186. * If you do not want this to happen, make a copy of `$data` before passing it
  187. * to this method
  188. *
  189. * @param array $data Record data to validate. This should be a numerically-indexed array
  190. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  191. * @return mixed If atomic: True on success, or false on failure.
  192. * Otherwise: array similar to the $data array passed, but values are set to true/false
  193. * depending on whether each record validated successfully.
  194. */
  195. public function validateMany(&$data, $options = array()) {
  196. $model = $this->getModel();
  197. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  198. $model->validationErrors = $validationErrors = $return = array();
  199. foreach ($data as $key => &$record) {
  200. if ($options['deep']) {
  201. $validates = $model->validateAssociated($record, $options);
  202. } else {
  203. $model->create(null);
  204. $validates = $model->set($record) && $model->validates($options);
  205. $data[$key] = $model->data;
  206. }
  207. if ($validates === false || (is_array($validates) && in_array(false, Hash::flatten($validates), true))) {
  208. $validationErrors[$key] = $model->validationErrors;
  209. $validates = false;
  210. } else {
  211. $validates = true;
  212. }
  213. $return[$key] = $validates;
  214. }
  215. $model->validationErrors = $validationErrors;
  216. if (!$options['atomic']) {
  217. return $return;
  218. }
  219. return empty($model->validationErrors);
  220. }
  221. /**
  222. * Returns an array of fields that have failed validation. On the current model. This method will
  223. * actually run validation rules over data, not just return the messages.
  224. *
  225. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  226. * @return array Array of invalid fields
  227. * @see ModelValidator::validates()
  228. */
  229. public function errors($options = array()) {
  230. if (!$this->_triggerBeforeValidate($options)) {
  231. return false;
  232. }
  233. $model = $this->getModel();
  234. if (!$this->_parseRules()) {
  235. return $model->validationErrors;
  236. }
  237. $fieldList = isset($options['fieldList']) ? $options['fieldList'] : array();
  238. $exists = $model->exists();
  239. $methods = $this->getMethods();
  240. $fields = $this->_validationList($fieldList);
  241. foreach ($fields as $field) {
  242. $field->setMethods($methods);
  243. $field->validationDomain($model->validationDomain);
  244. $data = isset($model->data[$model->alias]) ? $model->data[$model->alias] : array();
  245. $errors = $field->validate($data, $exists);
  246. foreach ($errors as $error) {
  247. $this->invalidate($field->field, $error);
  248. }
  249. }
  250. $model->getEventManager()->dispatch(new Event('Model.afterValidate', $model));
  251. return $model->validationErrors;
  252. }
  253. /**
  254. * Marks a field as invalid, optionally setting a message explaining
  255. * why the rule failed
  256. *
  257. * @param string $field The name of the field to invalidate
  258. * @param string $message Validation message explaining why the rule failed, defaults to true.
  259. * @return void
  260. */
  261. public function invalidate($field, $message = true) {
  262. $this->getModel()->validationErrors[$field][] = $message;
  263. }
  264. /**
  265. * Gets all possible custom methods from the Model and attached Behaviors
  266. * to be used as validators
  267. *
  268. * @return array List of callables to be used as validation methods
  269. */
  270. public function getMethods() {
  271. $behaviors = $this->_model->Behaviors->enabled();
  272. if (!empty($this->_methods) && $behaviors === $this->_behaviors) {
  273. return $this->_methods;
  274. }
  275. $this->_behaviors = $behaviors;
  276. if (empty($this->_modelMethods)) {
  277. foreach (get_class_methods($this->_model) as $method) {
  278. $this->_modelMethods[strtolower($method)] = array($this->_model, $method);
  279. }
  280. }
  281. $methods = $this->_modelMethods;
  282. foreach (array_keys($this->_model->Behaviors->methods()) as $method) {
  283. $methods += array(strtolower($method) => array($this->_model, $method));
  284. }
  285. return $this->_methods = $methods;
  286. }
  287. /**
  288. * Returns a Cake ValidationSet object containing all validation rules for a field, if no
  289. * params are passed then it returns an array with all Cake ValidationSet objects for each field
  290. *
  291. * @param string $name [optional] The fieldname to fetch. Defaults to null.
  292. * @return Cake\Model\Validator\ValidationSet|array
  293. */
  294. public function getField($name = null) {
  295. $this->_parseRules();
  296. if ($name !== null) {
  297. if (!empty($this->_fields[$name])) {
  298. return $this->_fields[$name];
  299. }
  300. return null;
  301. }
  302. return $this->_fields;
  303. }
  304. /**
  305. * Sets the Cake ValidationSet objects from the `Model::$validate` property
  306. * If `Model::$validate` is not set or empty, this method returns false. True otherwise.
  307. *
  308. * @return boolean true if `Model::$validate` was processed, false otherwise
  309. */
  310. protected function _parseRules() {
  311. if ($this->_validate === $this->_model->validate) {
  312. return true;
  313. }
  314. if (empty($this->_model->validate)) {
  315. $this->_validate = array();
  316. $this->_fields = array();
  317. return false;
  318. }
  319. $this->_validate = $this->_model->validate;
  320. $this->_fields = array();
  321. $methods = $this->getMethods();
  322. foreach ($this->_validate as $fieldName => $ruleSet) {
  323. $this->_fields[$fieldName] = new ValidationSet($fieldName, $ruleSet);
  324. $this->_fields[$fieldName]->setMethods($methods);
  325. }
  326. return true;
  327. }
  328. /**
  329. * Sets the I18n domain for validation messages. This method is chainable.
  330. *
  331. * @param string $validationDomain [optional] The validation domain to be used.
  332. * @return ModelValidator
  333. */
  334. public function setValidationDomain($validationDomain = null) {
  335. if (empty($validationDomain)) {
  336. $validationDomain = 'default';
  337. }
  338. $this->getModel()->validationDomain = $validationDomain;
  339. return $this;
  340. }
  341. /**
  342. * Gets the model related to this validator
  343. *
  344. * @return Model
  345. */
  346. public function getModel() {
  347. return $this->_model;
  348. }
  349. /**
  350. * Processes the Model's whitelist or passed fieldList and returns the list of fields
  351. * to be validated
  352. *
  353. * @param array $fieldList list of fields to be used for validation
  354. * @return array List of validation rules to be applied
  355. */
  356. protected function _validationList($fieldList = array()) {
  357. $model = $this->getModel();
  358. $whitelist = $model->whitelist;
  359. if (!empty($fieldList)) {
  360. if (!empty($fieldList[$model->alias]) && is_array($fieldList[$model->alias])) {
  361. $whitelist = $fieldList[$model->alias];
  362. } else {
  363. $whitelist = $fieldList;
  364. }
  365. }
  366. unset($fieldList);
  367. if (empty($whitelist) || Hash::dimensions($whitelist) > 1) {
  368. return $this->_fields;
  369. }
  370. $validateList = array();
  371. $this->validationErrors = array();
  372. foreach ((array)$whitelist as $f) {
  373. if (!empty($this->_fields[$f])) {
  374. $validateList[$f] = $this->_fields[$f];
  375. }
  376. }
  377. return $validateList;
  378. }
  379. /**
  380. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  381. * set and data in the data set.
  382. *
  383. * @param array $options Array of options to use on Validation of with models
  384. * @return boolean Failure of validation on with models.
  385. * @see Model::validates()
  386. */
  387. protected function _validateWithModels($options) {
  388. $valid = true;
  389. $model = $this->getModel();
  390. foreach ($model->hasAndBelongsToMany as $assoc => $association) {
  391. if (empty($association['with']) || !isset($model->data[$assoc])) {
  392. continue;
  393. }
  394. list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
  395. $data = $model->data[$assoc];
  396. $newData = array();
  397. foreach ((array)$data as $row) {
  398. if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  399. $newData[] = $row;
  400. } elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  401. $newData[] = $row[$join];
  402. }
  403. }
  404. foreach ($newData as $data) {
  405. $data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
  406. $model->{$join}->create($data);
  407. $valid = ($valid && $model->{$join}->validator()->validates($options));
  408. }
  409. }
  410. return $valid;
  411. }
  412. /**
  413. * Propagates beforeValidate event
  414. *
  415. * @param array $options
  416. * @return boolean
  417. */
  418. protected function _triggerBeforeValidate($options = array()) {
  419. $model = $this->getModel();
  420. $event = new Event('Model.beforeValidate', $model, array($options));
  421. list($event->break, $event->breakOn) = array(true, false);
  422. $model->getEventManager()->dispatch($event);
  423. if ($event->isStopped()) {
  424. return false;
  425. }
  426. return true;
  427. }
  428. /**
  429. * Returns whether a rule set is defined for a field or not
  430. *
  431. * @param string $field name of the field to check
  432. * @return boolean
  433. */
  434. public function offsetExists($field) {
  435. $this->_parseRules();
  436. return isset($this->_fields[$field]);
  437. }
  438. /**
  439. * Returns the rule set for a field
  440. *
  441. * @param string $field name of the field to check
  442. * @return Cake\Model\Validator\ValidationSet
  443. */
  444. public function offsetGet($field) {
  445. $this->_parseRules();
  446. return $this->_fields[$field];
  447. }
  448. /**
  449. * Sets the rule set for a field
  450. *
  451. * @param string $field name of the field to set
  452. * @param array|Cake\Model\Validator\ValidationSet $rules set of rules to apply to field
  453. * @return void
  454. */
  455. public function offsetSet($field, $rules) {
  456. $this->_parseRules();
  457. if (!$rules instanceof ValidationSet) {
  458. $rules = new ValidationSet($field, $rules);
  459. $methods = $this->getMethods();
  460. $rules->setMethods($methods);
  461. }
  462. $this->_fields[$field] = $rules;
  463. }
  464. /**
  465. * Unsets the rule set for a field
  466. *
  467. * @param string $field name of the field to unset
  468. * @return void
  469. */
  470. public function offsetUnset($field) {
  471. $this->_parseRules();
  472. unset($this->_fields[$field]);
  473. }
  474. /**
  475. * Returns an iterator for each of the fields to be validated
  476. *
  477. * @return ArrayIterator
  478. */
  479. public function getIterator() {
  480. $this->_parseRules();
  481. return new \ArrayIterator($this->_fields);
  482. }
  483. /**
  484. * Returns the number of fields having validation rules
  485. *
  486. * @return int
  487. */
  488. public function count() {
  489. $this->_parseRules();
  490. return count($this->_fields);
  491. }
  492. /**
  493. * Adds a new rule to a field's rule set. If second argumet is an array or instance of
  494. * Cake\Model\Validator\ValidationSet then rules list for the field will be replaced with second argument and
  495. * third argument will be ignored.
  496. *
  497. * ## Example:
  498. *
  499. * {{{
  500. * $validator
  501. * ->add('title', 'required', array('rule' => 'notEmpty', 'required' => true))
  502. * ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
  503. *
  504. * $validator->add('password', array(
  505. * 'size' => array('rule' => array('between', 8, 20)),
  506. * 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
  507. * ));
  508. * }}}
  509. *
  510. * @param string $field The name of the field from wich the rule will be removed
  511. * @param string|array|Cake\Model\Validator\ValidationSet $name name of the rule to be added or list of rules for the field
  512. * @param array|Cake\Model\Validator\ValidationRule $rule or list of rules to be added to the field's rule set
  513. * @return ModelValidator this instance
  514. */
  515. public function add($field, $name, $rule = null) {
  516. $this->_parseRules();
  517. if ($name instanceof ValidationSet) {
  518. $this->_fields[$field] = $name;
  519. return $this;
  520. }
  521. if (!isset($this->_fields[$field])) {
  522. $rule = (is_string($name)) ? array($name => $rule) : $name;
  523. $this->_fields[$field] = new ValidationSet($field, $rule);
  524. } else {
  525. if (is_string($name)) {
  526. $this->_fields[$field]->setRule($name, $rule);
  527. } else {
  528. $this->_fields[$field]->setRules($name);
  529. }
  530. }
  531. $methods = $this->getMethods();
  532. $this->_fields[$field]->setMethods($methods);
  533. return $this;
  534. }
  535. /**
  536. * Removes a rule from the set by its name
  537. *
  538. * ## Example:
  539. *
  540. * {{{
  541. * $validator
  542. * ->remove('title', 'required')
  543. * ->remove('user_id')
  544. * }}}
  545. *
  546. * @param string $field The name of the field from which the rule will be removed
  547. * @param string $rule the name of the rule to be removed
  548. * @return ModelValidator this instance
  549. */
  550. public function remove($field, $rule = null) {
  551. $this->_parseRules();
  552. if ($rule === null) {
  553. unset($this->_fields[$field]);
  554. } else {
  555. $this->_fields[$field]->removeRule($rule);
  556. }
  557. return $this;
  558. }
  559. }