ModelValidator.php 17 KB

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