ModelValidator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 += $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 = $model->whitelist;
  236. if (empty($fieldList) && !empty($options['fieldList'])) {
  237. if (!empty($options['fieldList'][$model->alias]) && is_array($options['fieldList'][$model->alias])) {
  238. $fieldList = $options['fieldList'][$model->alias];
  239. } else {
  240. $fieldList = $options['fieldList'];
  241. }
  242. }
  243. $exists = $model->exists();
  244. $methods = $this->getMethods();
  245. $fields = $this->_validationList($fieldList);
  246. foreach ($fields as $field) {
  247. $field->setMethods($methods);
  248. $field->setValidationDomain($model->validationDomain);
  249. $data = isset($model->data[$model->alias]) ? $model->data[$model->alias] : array();
  250. $errors = $field->validate($data, $exists);
  251. foreach ($errors as $error) {
  252. $this->invalidate($field->field, $error);
  253. }
  254. }
  255. $model->getEventManager()->dispatch(new CakeEvent('Model.afterValidate', $model));
  256. return $model->validationErrors;
  257. }
  258. /**
  259. * Marks a field as invalid, optionally setting a message explaining
  260. * why the rule failed
  261. *
  262. * @param string $field The name of the field to invalidate
  263. * @param string $message Validation message explaining why the rule failed, defaults to true.
  264. * @return void
  265. */
  266. public function invalidate($field, $message = true) {
  267. $this->getModel()->validationErrors[$field][] = $message;
  268. }
  269. /**
  270. * Gets all possible custom methods from the Model and attached Behaviors
  271. * to be used as validators
  272. *
  273. * @return array List of callables to be used as validation methods
  274. */
  275. public function getMethods() {
  276. $behaviors = $this->_model->Behaviors->enabled();
  277. if (!empty($this->_methods) && $behaviors === $this->_behaviors) {
  278. return $this->_methods;
  279. }
  280. $this->_behaviors = $behaviors;
  281. if (empty($this->_modelMethods)) {
  282. foreach (get_class_methods($this->_model) as $method) {
  283. $this->_modelMethods[strtolower($method)] = array($this->_model, $method);
  284. }
  285. }
  286. $methods = $this->_modelMethods;
  287. foreach (array_keys($this->_model->Behaviors->methods()) as $method) {
  288. $methods += array(strtolower($method) => array($this->_model, $method));
  289. }
  290. return $this->_methods = $methods;
  291. }
  292. /**
  293. * Returns a CakeValidationSet object containing all validation rules for a field, if no
  294. * params are passed then it returns an array with all CakeValidationSet objects for each field
  295. *
  296. * @param string $name [optional] The fieldname to fetch. Defaults to null.
  297. * @return CakeValidationSet|array
  298. */
  299. public function getField($name = null) {
  300. $this->_parseRules();
  301. if ($name !== null) {
  302. if (!empty($this->_fields[$name])) {
  303. return $this->_fields[$name];
  304. }
  305. return null;
  306. }
  307. return $this->_fields;
  308. }
  309. /**
  310. * Sets the CakeValidationSet objects from the `Model::$validate` property
  311. * If `Model::$validate` is not set or empty, this method returns false. True otherwise.
  312. *
  313. * @return boolean true if `Model::$validate` was processed, false otherwise
  314. */
  315. protected function _parseRules() {
  316. if ($this->_validate === $this->_model->validate) {
  317. return true;
  318. }
  319. if (empty($this->_model->validate)) {
  320. $this->_validate = array();
  321. $this->_fields = array();
  322. return false;
  323. }
  324. $this->_validate = $this->_model->validate;
  325. $this->_fields = array();
  326. $methods = $this->getMethods();
  327. foreach ($this->_validate as $fieldName => $ruleSet) {
  328. $this->_fields[$fieldName] = new CakeValidationSet($fieldName, $ruleSet);
  329. $this->_fields[$fieldName]->setMethods($methods);
  330. }
  331. return true;
  332. }
  333. /**
  334. * Sets the I18n domain for validation messages. This method is chainable.
  335. *
  336. * @param string $validationDomain [optional] The validation domain to be used.
  337. * @return ModelValidator
  338. */
  339. public function setValidationDomain($validationDomain = null) {
  340. if (empty($validationDomain)) {
  341. $validationDomain = 'default';
  342. }
  343. $this->getModel()->validationDomain = $validationDomain;
  344. return $this;
  345. }
  346. /**
  347. * Gets the model related to this validator
  348. *
  349. * @return Model
  350. */
  351. public function getModel() {
  352. return $this->_model;
  353. }
  354. /**
  355. * Processes the passed fieldList and returns the list of fields to be validated
  356. *
  357. * @param array $fieldList list of fields to be used for validation
  358. * @return array List of validation rules to be applied
  359. */
  360. protected function _validationList($fieldList = array()) {
  361. if (empty($fieldList) || Hash::dimensions($fieldList) > 1) {
  362. return $this->_fields;
  363. }
  364. $validateList = array();
  365. $this->validationErrors = array();
  366. foreach ((array)$fieldList as $f) {
  367. if (!empty($this->_fields[$f])) {
  368. $validateList[$f] = $this->_fields[$f];
  369. }
  370. }
  371. return $validateList;
  372. }
  373. /**
  374. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  375. * set and data in the data set.
  376. *
  377. * @param array $options Array of options to use on Validation of with models
  378. * @return boolean Failure of validation on with models.
  379. * @see Model::validates()
  380. */
  381. protected function _validateWithModels($options) {
  382. $valid = true;
  383. $model = $this->getModel();
  384. foreach ($model->hasAndBelongsToMany as $assoc => $association) {
  385. if (empty($association['with']) || !isset($model->data[$assoc])) {
  386. continue;
  387. }
  388. list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
  389. $data = $model->data[$assoc];
  390. $newData = array();
  391. foreach ((array)$data as $row) {
  392. if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  393. $newData[] = $row;
  394. } elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  395. $newData[] = $row[$join];
  396. }
  397. }
  398. foreach ($newData as $data) {
  399. $data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
  400. $model->{$join}->create($data);
  401. $valid = ($valid && $model->{$join}->validator()->validates($options));
  402. }
  403. }
  404. return $valid;
  405. }
  406. /**
  407. * Propagates beforeValidate event
  408. *
  409. * @param array $options
  410. * @return boolean
  411. */
  412. protected function _triggerBeforeValidate($options = array()) {
  413. $model = $this->getModel();
  414. $event = new CakeEvent('Model.beforeValidate', $model, array($options));
  415. list($event->break, $event->breakOn) = array(true, false);
  416. $model->getEventManager()->dispatch($event);
  417. if ($event->isStopped()) {
  418. return false;
  419. }
  420. return true;
  421. }
  422. /**
  423. * Returns whether a rule set is defined for a field or not
  424. *
  425. * @param string $field name of the field to check
  426. * @return boolean
  427. */
  428. public function offsetExists($field) {
  429. $this->_parseRules();
  430. return isset($this->_fields[$field]);
  431. }
  432. /**
  433. * Returns the rule set for a field
  434. *
  435. * @param string $field name of the field to check
  436. * @return CakeValidationSet
  437. */
  438. public function offsetGet($field) {
  439. $this->_parseRules();
  440. return $this->_fields[$field];
  441. }
  442. /**
  443. * Sets the rule set for a field
  444. *
  445. * @param string $field name of the field to set
  446. * @param array|CakeValidationSet $rules set of rules to apply to field
  447. * @return void
  448. */
  449. public function offsetSet($field, $rules) {
  450. $this->_parseRules();
  451. if (!$rules instanceof CakeValidationSet) {
  452. $rules = new CakeValidationSet($field, $rules);
  453. $methods = $this->getMethods();
  454. $rules->setMethods($methods);
  455. }
  456. $this->_fields[$field] = $rules;
  457. }
  458. /**
  459. * Unsets the rule set for a field
  460. *
  461. * @param string $field name of the field to unset
  462. * @return void
  463. */
  464. public function offsetUnset($field) {
  465. $this->_parseRules();
  466. unset($this->_fields[$field]);
  467. }
  468. /**
  469. * Returns an iterator for each of the fields to be validated
  470. *
  471. * @return ArrayIterator
  472. */
  473. public function getIterator() {
  474. $this->_parseRules();
  475. return new ArrayIterator($this->_fields);
  476. }
  477. /**
  478. * Returns the number of fields having validation rules
  479. *
  480. * @return integer
  481. */
  482. public function count() {
  483. $this->_parseRules();
  484. return count($this->_fields);
  485. }
  486. /**
  487. * Adds a new rule to a field's rule set. If second argument is an array or instance of
  488. * CakeValidationSet then rules list for the field will be replaced with second argument and
  489. * third argument will be ignored.
  490. *
  491. * ## Example:
  492. *
  493. * {{{
  494. * $validator
  495. * ->add('title', 'required', array('rule' => 'notEmpty', 'required' => true))
  496. * ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
  497. *
  498. * $validator->add('password', array(
  499. * 'size' => array('rule' => array('between', 8, 20)),
  500. * 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
  501. * ));
  502. * }}}
  503. *
  504. * @param string $field The name of the field from which the rule will be removed
  505. * @param string|array|CakeValidationSet $name name of the rule to be added or list of rules for the field
  506. * @param array|CakeValidationRule $rule or list of rules to be added to the field's rule set
  507. * @return ModelValidator this instance
  508. */
  509. public function add($field, $name, $rule = null) {
  510. $this->_parseRules();
  511. if ($name instanceof CakeValidationSet) {
  512. $this->_fields[$field] = $name;
  513. return $this;
  514. }
  515. if (!isset($this->_fields[$field])) {
  516. $rule = (is_string($name)) ? array($name => $rule) : $name;
  517. $this->_fields[$field] = new CakeValidationSet($field, $rule);
  518. } else {
  519. if (is_string($name)) {
  520. $this->_fields[$field]->setRule($name, $rule);
  521. } else {
  522. $this->_fields[$field]->setRules($name);
  523. }
  524. }
  525. $methods = $this->getMethods();
  526. $this->_fields[$field]->setMethods($methods);
  527. return $this;
  528. }
  529. /**
  530. * Removes a rule from the set by its name
  531. *
  532. * ## Example:
  533. *
  534. * {{{
  535. * $validator
  536. * ->remove('title', 'required')
  537. * ->remove('user_id')
  538. * }}}
  539. *
  540. * @param string $field The name of the field from which the rule will be removed
  541. * @param string $rule the name of the rule to be removed
  542. * @return ModelValidator this instance
  543. */
  544. public function remove($field, $rule = null) {
  545. $this->_parseRules();
  546. if ($rule === null) {
  547. unset($this->_fields[$field]);
  548. } else {
  549. $this->_fields[$field]->removeRule($rule);
  550. }
  551. return $this;
  552. }
  553. }