ModelValidator.php 18 KB

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