ModelValidator.php 18 KB

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