ModelValidator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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-2011, 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-2011, 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('CakeField', 'Model/Validator');
  22. App::uses('CakeRule', 'Model/Validator');
  23. /**
  24. * ModelValidator object.
  25. *
  26. * @package Cake.Model
  27. * @link http://book.cakephp.org/2.0/en/data-validation.html
  28. */
  29. class ModelValidator {
  30. /**
  31. * The default ModelValidator class name
  32. *
  33. * @var string
  34. */
  35. const DEFAULT_VALIDATOR = 'ModelValidator';
  36. /**
  37. * The default validation domain
  38. *
  39. * @var string
  40. */
  41. const DEFAULT_DOMAIN = 'default';
  42. /**
  43. * Holds the data array from the Model
  44. *
  45. * @var array
  46. */
  47. public $data = array();
  48. /**
  49. * The default ValidationDomain
  50. *
  51. * @var string
  52. */
  53. public $validationDomain = 'default';
  54. /**
  55. * Holds the validationErrors
  56. *
  57. * @var array
  58. */
  59. public $validationErrors = array();
  60. /**
  61. * Holds the options
  62. *
  63. * @var array
  64. */
  65. public $options = array();
  66. /**
  67. * Holds the CakeField objects array
  68. *
  69. * @var array
  70. */
  71. protected $_fields = array();
  72. /**
  73. * Holds the reference to the model the Validator is attached to
  74. *
  75. * @var Model
  76. */
  77. protected $_model = array();
  78. /**
  79. * The validators $validate property
  80. *
  81. * @var array
  82. */
  83. protected $_validate = array();
  84. /**
  85. * Holds the available custom callback methods
  86. *
  87. * @var array
  88. */
  89. protected $_methods = array();
  90. /**
  91. * Constructor
  92. *
  93. * @param Model $Model A reference to the Model the Validator is attached to
  94. */
  95. public function __construct(Model $Model) {
  96. $this->_model = $Model;
  97. }
  98. /**
  99. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  100. * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
  101. *
  102. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  103. *
  104. * @param array $options An optional array of custom options to be made available in the beforeValidate callback
  105. * @return boolean True if there are no errors
  106. */
  107. public function validates($options = array()) {
  108. $this->validationErrors = array();
  109. $errors = $this->invalidFields($options);
  110. if (empty($errors) && $errors !== false) {
  111. $errors = $this->_validateWithModels($options);
  112. }
  113. if (is_array($errors)) {
  114. return count($errors) === 0;
  115. }
  116. return $errors;
  117. }
  118. /**
  119. * Validates a single record, as well as all its directly associated records.
  120. *
  121. * #### Options
  122. *
  123. * - atomic: If true (default), returns boolean. If false returns array.
  124. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  125. * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
  126. *
  127. * @param array $data Record data to validate. This should be an array indexed by association name.
  128. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  129. * @return array|boolean If atomic: True on success, or false on failure.
  130. * Otherwise: array similar to the $data array passed, but values are set to true/false
  131. * depending on whether each record validated successfully.
  132. */
  133. public function validateAssociated($data, $options = array()) {
  134. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  135. $this->validationErrors = $this->getModel()->validationErrors = $return = array();
  136. if (!($this->getModel()->create($data) && $this->validates($options))) {
  137. $this->validationErrors = array($this->getModel()->alias => $this->validationErrors);
  138. $return[$this->getModel()->alias] = false;
  139. } else {
  140. $return[$this->getModel()->alias] = true;
  141. }
  142. $associations = $this->getModel()->getAssociated();
  143. foreach ($data as $association => $values) {
  144. $validates = true;
  145. if (isset($associations[$association])) {
  146. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  147. if ($options['deep']) {
  148. $validates = $this->getModel()->{$association}->getValidator()->validateAssociated($values, $options);
  149. } else {
  150. $validates = $this->getModel()->{$association}->create($values) !== null && $this->getModel()->{$association}->getValidator()->validates($options);
  151. }
  152. if (is_array($validates)) {
  153. if (in_array(false, $validates, true)) {
  154. $validates = false;
  155. } else {
  156. $validates = true;
  157. }
  158. }
  159. $return[$association] = $validates;
  160. } elseif ($associations[$association] === 'hasMany') {
  161. $validates = $this->getModel()->{$association}->getValidator()->validateMany($values, $options);
  162. $return[$association] = $validates;
  163. }
  164. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  165. $this->validationErrors[$association] = $this->getModel()->{$association}->getValidator()->validationErrors;
  166. }
  167. }
  168. }
  169. if (isset($this->validationErrors[$this->getModel()->alias])) {
  170. $this->validationErrors = $this->validationErrors[$this->getModel()->alias];
  171. }
  172. $this->getModel()->validationErrors = $this->validationErrors;
  173. if (!$options['atomic']) {
  174. return $return;
  175. }
  176. if ($return[$this->getModel()->alias] === false || !empty($this->validationErrors)) {
  177. return false;
  178. }
  179. return true;
  180. }
  181. /**
  182. * Validates multiple individual records for a single model
  183. *
  184. * #### Options
  185. *
  186. * - atomic: If true (default), returns boolean. If false returns array.
  187. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  188. * - deep: If set to true, all associated data will be validated as well.
  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. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  199. $this->validationErrors = $validationErrors = $this->getModel()->validationErrors = $return = array();
  200. foreach ($data as $key => $record) {
  201. if ($options['deep']) {
  202. $validates = $this->validateAssociated($record, $options);
  203. } else {
  204. $validates = $this->getModel()->create($record) && $this->validates($options);
  205. }
  206. if ($validates === false || (is_array($validates) && in_array(false, $validates, true))) {
  207. $validationErrors[$key] = $this->validationErrors;
  208. $validates = false;
  209. } else {
  210. $validates = true;
  211. }
  212. $return[$key] = $validates;
  213. }
  214. $this->validationErrors = $this->getModel()->validationErrors = $validationErrors;
  215. if (!$options['atomic']) {
  216. return $return;
  217. }
  218. if (empty($this->validationErrors)) {
  219. return true;
  220. }
  221. return false;
  222. }
  223. /**
  224. * Returns an array of fields that have failed validation. On the current model.
  225. *
  226. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  227. * @return array Array of invalid fields
  228. * @see Model::validates()
  229. */
  230. public function invalidFields($options = array()) {
  231. if (!$this->propagateBeforeValidate($options)) {
  232. return false;
  233. }
  234. $this->data = array();
  235. $this->setOptions($options);
  236. if (!$this->setFields()) {
  237. return $this->getModel()->validationErrors = $this->validationErrors;
  238. }
  239. $this->getData();
  240. $this->getMethods();
  241. $this->setValidationDomain();
  242. foreach ($this->_fields as $field) {
  243. $field->validate();
  244. }
  245. $this->setFields(true);
  246. return $this->getModel()->validationErrors = $this->validationErrors;
  247. }
  248. /**
  249. * Marks a field as invalid, optionally setting the name of validation
  250. * rule (in case of multiple validation for field) that was broken.
  251. *
  252. * @param string $field The name of the field to invalidate
  253. * @param mixed $value Name of validation rule that was not failed, or validation message to
  254. * be returned. If no validation key is provided, defaults to true.
  255. * @return void
  256. */
  257. public function invalidate($field, $value = true) {
  258. if (!is_array($this->validationErrors)) {
  259. $this->validationErrors = array();
  260. }
  261. $this->validationErrors[$field][] = $this->getModel()->validationErrors[$field][] = $value;
  262. }
  263. /**
  264. * Gets the current data from the model and sets it to $this->data
  265. *
  266. * @param string $field [optional]
  267. * @return array The data
  268. */
  269. public function getData($field = null, $all = false) {
  270. if (!empty($this->data)) {
  271. if ($field !== null && isset($this->data[$field])) {
  272. return $this->data[$field];
  273. }
  274. return $this->data;
  275. }
  276. $this->data = $this->_model->data;
  277. if (FALSE === $all && isset($this->data[$this->_model->alias])) {
  278. $this->data = $this->data[$this->_model->alias];
  279. } elseif (!is_array($this->data)) {
  280. $this->data = array();
  281. }
  282. if ($field !== null && isset($this->data[$field])) {
  283. return $this->data[$field];
  284. }
  285. return $this->data;
  286. }
  287. /**
  288. * Gets all possible custom methods from the Model, Behaviors and the Validator.
  289. * If $type is null (default) gets all methods. If $type is one of 'model', 'behaviors' or 'validator',
  290. * gets the corresponding methods.
  291. *
  292. * @param string $type [optional] The methods type to get. Defaults to null
  293. * @return array The requested methods
  294. */
  295. public function getMethods($type = null) {
  296. if (!empty($this->_methods)) {
  297. if ($type !== null && !empty($this->_methods[$type])) {
  298. return $this->_methods[$type];
  299. }
  300. return $this->_methods;
  301. }
  302. $this->_methods['model'] = array_map('strtolower', get_class_methods($this->_model));
  303. $this->_methods['behaviors'] = array_keys($this->_model->Behaviors->methods());
  304. $this->_methods['validator'] = get_class_methods($this);
  305. if ($type !== null && !empty($this->_methods[$type])) {
  306. return $this->_methods[$type];
  307. }
  308. unset($type);
  309. return $this->_methods;
  310. }
  311. /**
  312. * Gets all fields if $name is null (default), or the field for fieldname $name if it's found.
  313. *
  314. * @param string $name [optional] The fieldname to fetch. Defaults to null.
  315. * @return mixed Either array of CakeField objects , single object for $name or false when $name not present in fields
  316. */
  317. public function getFields($name = null) {
  318. if ($name !== null && !empty($this->_fields[$name])) {
  319. return $this->_fields[$name];
  320. } elseif ($name !==null) {
  321. return false;
  322. }
  323. return $this->_fields;
  324. }
  325. /**
  326. * Sets the CakeField isntances from the Model::$validate property after processing the fieldList and whiteList.
  327. * If Model::$validate is not set or empty, this method returns false. True otherwise.
  328. *
  329. * @param boolean $reset If true will reset the Validator $validate array to the Model's default
  330. * @return boolean True if Model::$validate was processed, false otherwise
  331. */
  332. public function setFields($reset = false) {
  333. if (!isset($this->_model->validate) || empty($this->_model->validate)) {
  334. $this->_validate = array();
  335. return false;
  336. }
  337. $this->_validate = $this->_model->validate;
  338. if ($reset === true) {
  339. return true;
  340. }
  341. $this->_processWhitelist();
  342. $this->_fields = array();
  343. foreach ($this->_validate as $fieldName => $ruleSet) {
  344. $this->_fields[$fieldName] = new CakeField($this, $fieldName, $ruleSet);
  345. }
  346. unset($fieldName, $ruleSet);
  347. return true;
  348. }
  349. /**
  350. * Sets an options array. If $mergeVars is true, the options will be merged with the existing ones.
  351. * Otherwise they will get replaced. The default is merging the vars.
  352. *
  353. * @param array $options [optional] The options to be set
  354. * @param boolean $mergeVars [optional] If true, the options will be merged, otherwise they get replaced
  355. * @return ModelValidator
  356. */
  357. public function setOptions($options = array(), $mergeVars = false) {
  358. if ($mergeVars === false) {
  359. $this->options = $options;
  360. } else {
  361. $this->options = array_merge($this->options, $options);
  362. }
  363. return $this;
  364. }
  365. /**
  366. * Sets an option $name with $value. This method is chainable
  367. *
  368. * @param string $name The options name to be set
  369. * @param mixed $value [optional] The value to be set. Defaults to null.
  370. * @return ModelValidator
  371. */
  372. public function setOption($name, $value = null) {
  373. $this->options[$name] = $value;
  374. return $this;
  375. }
  376. /**
  377. * Gets an options value by $name. If $name is not set or no option has been found, returns null.
  378. *
  379. * @param string $name The options name to look up
  380. * @return mixed Either null or the option value
  381. */
  382. public function getOptions($name = NULL) {
  383. if (NULL !== $name) {
  384. if (!isset($this->options[$name])) {
  385. return NULL;
  386. }
  387. return $this->options[$name];
  388. }
  389. return $this->options;
  390. }
  391. /**
  392. * Sets the I18n domain for validation messages. This method is chainable.
  393. *
  394. * @param string $validationDomain [optional] The validation domain to be used. If none is given, uses Model::$validationDomain
  395. * @return ModelValidator
  396. */
  397. public function setValidationDomain($validationDomain = null) {
  398. if ($validationDomain !== null) {
  399. $this->validationDomain = $validationDomain;
  400. } elseif ($this->_model->validationDomain !== null) {
  401. $this->validationDomain = $this->_model->validationDomain;
  402. } else {
  403. $this->validationDomain = ModelValidator::DEFAULT_DOMAIN;
  404. }
  405. return $this;
  406. }
  407. /**
  408. * Gets the parent Model
  409. *
  410. * @return Model
  411. */
  412. public function getModel() {
  413. return $this->_model;
  414. }
  415. /**
  416. * Processes the Model's whitelist and adjusts the validate array accordingly
  417. *
  418. * @return void
  419. */
  420. protected function _processWhitelist() {
  421. $whitelist = $this->getModel()->whitelist;
  422. $fieldList = $this->getOptions('fieldList');
  423. if (!empty($fieldList)) {
  424. if (!empty($fieldList[$this->getModel()->alias]) && is_array($fieldList[$this->getModel()->alias])) {
  425. $whitelist = $fieldList[$this->getModel()->alias];
  426. } else {
  427. $whitelist = $fieldList;
  428. }
  429. }
  430. unset($fieldList);
  431. if (!empty($whitelist)) {
  432. $this->validationErrors = array();
  433. $validate = array();
  434. foreach ((array) $whitelist as $f) {
  435. if (!empty($this->_validate[$f])) {
  436. $validate[$f] = $this->_validate[$f];
  437. }
  438. }
  439. $this->_validate = $validate;
  440. }
  441. }
  442. /**
  443. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  444. * set. And data in the set() data set.
  445. *
  446. * @param array $options Array of options to use on Validation of with models
  447. * @return boolean Failure of validation on with models.
  448. * @see Model::validates()
  449. */
  450. protected function _validateWithModels($options) {
  451. $valid = true;
  452. $this->getData(null, true);
  453. foreach ($this->getModel()->hasAndBelongsToMany as $assoc => $association) {
  454. if (empty($association['with']) || !isset($this->data[$assoc])) {
  455. continue;
  456. }
  457. list($join) = $this->getModel()->joinModel($this->getModel()->hasAndBelongsToMany[$assoc]['with']);
  458. $data = $this->data[$assoc];
  459. $newData = array();
  460. foreach ((array)$data as $row) {
  461. if (isset($row[$this->getModel()->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  462. $newData[] = $row;
  463. } elseif (isset($row[$join]) && isset($row[$join][$this->getModel()->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  464. $newData[] = $row[$join];
  465. }
  466. }
  467. if (empty($newData)) {
  468. continue;
  469. }
  470. foreach ($newData as $data) {
  471. $data[$this->getModel()->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->getModel()->id;
  472. $this->getModel()->{$join}->create($data);
  473. $valid = ($valid && $this->getModel()->{$join}->getValidator()->validates($options));
  474. }
  475. }
  476. return $valid;
  477. }
  478. /**
  479. * Propagates the beforeValidate event
  480. *
  481. * @param array $options
  482. * @return boolean
  483. */
  484. public function propagateBeforeValidate($options = array()) {
  485. $event = new CakeEvent('Model.beforeValidate', $this->getModel(), array($options));
  486. list($event->break, $event->breakOn) = array(true, false);
  487. $this->getModel()->getEventManager()->dispatch($event);
  488. if ($event->isStopped()) {
  489. return false;
  490. }
  491. return true;
  492. }
  493. }