ModelValidator.php 18 KB

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