ModelValidator.php 18 KB

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