ModelValidator.php 18 KB

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