ModelValidator.php 18 KB

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