ModelValidator.php 18 KB

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