ModelValidator.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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('CakeValidationSet', '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. * Holds the CakeValidationSet objects array
  32. *
  33. * @var array
  34. */
  35. protected $_fields = array();
  36. /**
  37. * Holds the reference to the model the Validator is attached to
  38. *
  39. * @var Model
  40. */
  41. protected $_model = array();
  42. /**
  43. * The validators $validate property
  44. *
  45. * @var array
  46. */
  47. protected $_validate = array();
  48. /**
  49. * Holds the available custom callback methods
  50. *
  51. * @var array
  52. */
  53. protected $_methods = array();
  54. /**
  55. * Constructor
  56. *
  57. * @param Model $Model A reference to the Model the Validator is attached to
  58. */
  59. public function __construct(Model $Model) {
  60. $this->_model = $Model;
  61. }
  62. /**
  63. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  64. * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
  65. *
  66. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  67. *
  68. * @param array $options An optional array of custom options to be made available in the beforeValidate callback
  69. * @return boolean True if there are no errors
  70. */
  71. public function validates($options = array()) {
  72. $errors = $this->errors($options);
  73. if (empty($errors) && $errors !== false) {
  74. $errors = $this->_validateWithModels($options);
  75. }
  76. if (is_array($errors)) {
  77. return count($errors) === 0;
  78. }
  79. return $errors;
  80. }
  81. /**
  82. * Validates a single record, as well as all its directly associated records.
  83. *
  84. * #### Options
  85. *
  86. * - atomic: If true (default), returns boolean. If false returns array.
  87. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  88. * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
  89. *
  90. * @param array $data Record data to validate. This should be an array indexed by association name.
  91. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  92. * @return array|boolean If atomic: True on success, or false on failure.
  93. * Otherwise: array similar to the $data array passed, but values are set to true/false
  94. * depending on whether each record validated successfully.
  95. */
  96. public function validateAssociated($data, $options = array()) {
  97. $model = $this->getModel();
  98. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  99. $model->validationErrors = $validationErrors = $return = array();
  100. if (!($model->create($data) && $model->validates($options))) {
  101. $validationErrors[$model->alias] = $model->validationErrors;
  102. $return[$model->alias] = false;
  103. } else {
  104. $return[$model->alias] = true;
  105. }
  106. $associations = $model->getAssociated();
  107. foreach ($data as $association => $values) {
  108. $validates = true;
  109. if (isset($associations[$association])) {
  110. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  111. if ($options['deep']) {
  112. $validates = $model->{$association}->validateAssociated($values, $options);
  113. } else {
  114. $validates = $model->{$association}->create($values) !== null && $model->{$association}->validates($options);
  115. }
  116. if (is_array($validates)) {
  117. if (in_array(false, $validates, true)) {
  118. $validates = false;
  119. } else {
  120. $validates = true;
  121. }
  122. }
  123. $return[$association] = $validates;
  124. } elseif ($associations[$association] === 'hasMany') {
  125. $validates = $model->{$association}->validateMany($values, $options);
  126. $return[$association] = $validates;
  127. }
  128. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  129. $validationErrors[$association] = $model->{$association}->validationErrors;
  130. }
  131. }
  132. }
  133. $model->validationErrors = $validationErrors;
  134. if (isset($validationErrors[$model->alias])) {
  135. $model->validationErrors = $validationErrors[$model->alias];
  136. }
  137. if (!$options['atomic']) {
  138. return $return;
  139. }
  140. if ($return[$model->alias] === false || !empty($model->validationErrors)) {
  141. return false;
  142. }
  143. return true;
  144. }
  145. /**
  146. * Validates multiple individual records for a single model
  147. *
  148. * #### Options
  149. *
  150. * - atomic: If true (default), returns boolean. If false returns array.
  151. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  152. * - deep: If set to true, all associated data will be validated as well.
  153. *
  154. * @param array $data Record data to validate. This should be a numerically-indexed array
  155. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  156. * @return boolean True on success, or false on failure.
  157. * @return mixed If atomic: True on success, or false on failure.
  158. * Otherwise: array similar to the $data array passed, but values are set to true/false
  159. * depending on whether each record validated successfully.
  160. */
  161. public function validateMany($data, $options = array()) {
  162. $model = $this->getModel();
  163. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  164. $model->validationErrors = $validationErrors = $return = array();
  165. foreach ($data as $key => $record) {
  166. if ($options['deep']) {
  167. $validates = $model->validateAssociated($record, $options);
  168. } else {
  169. $validates = $model->create($record) && $model->validates($options);
  170. }
  171. if ($validates === false || (is_array($validates) && in_array(false, $validates, true))) {
  172. $validationErrors[$key] = $model->validationErrors;
  173. $validates = false;
  174. } else {
  175. $validates = true;
  176. }
  177. $return[$key] = $validates;
  178. }
  179. $model->validationErrors = $validationErrors;
  180. if (!$options['atomic']) {
  181. return $return;
  182. }
  183. if (empty($model->validationErrors)) {
  184. return true;
  185. }
  186. return false;
  187. }
  188. /**
  189. * Returns an array of fields that have failed validation. On the current model.
  190. *
  191. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  192. * @return array Array of invalid fields
  193. * @see Model::validates()
  194. */
  195. public function errors($options = array()) {
  196. if (!$this->_triggerBeforeValidate($options)) {
  197. return false;
  198. }
  199. $model = $this->getModel();
  200. if (!$this->_parseRules()) {
  201. return $model->validationErrors;
  202. }
  203. $fieldList = isset($options['fieldList']) ? $options['fieldList'] : array();
  204. $exists = $model->exists();
  205. $methods = $this->getMethods();
  206. $fields = $this->_validationList($fieldList);
  207. foreach ($fields as $field) {
  208. $field->setMethods($methods);
  209. $field->setValidationDomain($model->validationDomain);
  210. $data = isset($model->data[$model->alias]) ? $model->data[$model->alias] : array();
  211. $errors = $field->validate($data, $exists);
  212. foreach ($errors as $error) {
  213. $this->invalidate($field->field, $error);
  214. }
  215. }
  216. return $model->validationErrors;
  217. }
  218. /**
  219. * Marks a field as invalid, optionally setting the name of validation
  220. * rule (in case of multiple validation for field) that was broken.
  221. *
  222. * @param string $field The name of the field to invalidate
  223. * @param string $value Name of validation rule that failed, or validation message to
  224. * be returned. If no validation key is provided, defaults to true.
  225. * @return void
  226. */
  227. public function invalidate($field, $value = true) {
  228. $this->getModel()->validationErrors[$field][] = $value;
  229. }
  230. /**
  231. * Gets all possible custom methods from the Model, Behaviors and the Validator.
  232. * gets the corresponding methods.
  233. *
  234. * @return array The requested methods
  235. */
  236. public function getMethods() {
  237. if (!empty($this->_methods)) {
  238. return $this->_methods;
  239. }
  240. $methods = array();
  241. foreach (get_class_methods($this->_model) as $method) {
  242. $methods[strtolower($method)] = array($this->_model, $method);
  243. }
  244. foreach (array_keys($this->_model->Behaviors->methods()) as $mthod) {
  245. $methods += array(strtolower($method) => array($this->_model, $method));
  246. }
  247. return $this->_methods = $methods;
  248. }
  249. /**
  250. * Gets all fields if $name is null (default), or the field for fieldname $name if it's found.
  251. *
  252. * @param string $name [optional] The fieldname to fetch. Defaults to null.
  253. * @return mixed Either array of CakeValidationSet objects , single object for $name or false when $name not present in fields
  254. */
  255. public function getFields($name = null) {
  256. if ($name !== null && !empty($this->_fields[$name])) {
  257. return $this->_fields[$name];
  258. } elseif ($name !==null) {
  259. return false;
  260. }
  261. return $this->_fields;
  262. }
  263. /**
  264. * Sets the CakeValidationSet instances from the Model::$validate property after processing the fieldList and whiteList.
  265. * If Model::$validate is not set or empty, this method returns false. True otherwise.
  266. *
  267. * @return boolean True if Model::$validate was processed, false otherwise
  268. */
  269. protected function _parseRules() {
  270. if (empty($this->_model->validate)) {
  271. $this->_validate = array();
  272. $this->_fields = array();
  273. return false;
  274. }
  275. if ($this->_validate === $this->_model->validate) {
  276. return true;
  277. }
  278. $this->_validate = $this->_model->validate;
  279. $this->_fields = array();
  280. $methods = $this->getMethods();
  281. foreach ($this->_validate as $fieldName => $ruleSet) {
  282. $this->_fields[$fieldName] = new CakeValidationSet($fieldName, $ruleSet, $methods);
  283. }
  284. return true;
  285. }
  286. /**
  287. * Sets the I18n domain for validation messages. This method is chainable.
  288. *
  289. * @param string $validationDomain [optional] The validation domain to be used.
  290. * @return ModelValidator
  291. */
  292. public function setValidationDomain($validationDomain = null) {
  293. if (empty($validationDomain)) {
  294. $validationDomain = 'default';
  295. }
  296. $this->getModel()->validationDomain = $validationDomain;
  297. return $this;
  298. }
  299. /**
  300. * Gets the parent Model
  301. *
  302. * @return Model
  303. */
  304. public function getModel() {
  305. return $this->_model;
  306. }
  307. /**
  308. * Processes the Model's whitelist and returns the list of fields
  309. * to be validated
  310. *
  311. * @return array List of validation rules to be applied
  312. */
  313. protected function _validationList($fieldList = array()) {
  314. $model = $this->getModel();
  315. $whitelist = $model->whitelist;
  316. if (!empty($fieldList)) {
  317. if (!empty($fieldList[$model->alias]) && is_array($fieldList[$model->alias])) {
  318. $whitelist = $fieldList[$model->alias];
  319. } else {
  320. $whitelist = $fieldList;
  321. }
  322. }
  323. unset($fieldList);
  324. $validateList = array();
  325. if (!empty($whitelist)) {
  326. $this->validationErrors = array();
  327. foreach ((array)$whitelist as $f) {
  328. if (!empty($this->_fields[$f])) {
  329. $validateList[$f] = $this->_fields[$f];
  330. }
  331. }
  332. } else {
  333. return $this->_fields;
  334. }
  335. return $validateList;
  336. }
  337. /**
  338. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  339. * set. And data in the set() data set.
  340. *
  341. * @param array $options Array of options to use on Validation of with models
  342. * @return boolean Failure of validation on with models.
  343. * @see Model::validates()
  344. */
  345. protected function _validateWithModels($options) {
  346. $valid = true;
  347. $model = $this->getModel();
  348. foreach ($model->hasAndBelongsToMany as $assoc => $association) {
  349. if (empty($association['with']) || !isset($model->data[$assoc])) {
  350. continue;
  351. }
  352. list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
  353. $data = $model->data[$assoc];
  354. $newData = array();
  355. foreach ((array)$data as $row) {
  356. if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  357. $newData[] = $row;
  358. } elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  359. $newData[] = $row[$join];
  360. }
  361. }
  362. if (empty($newData)) {
  363. continue;
  364. }
  365. foreach ($newData as $data) {
  366. $data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
  367. $model->{$join}->create($data);
  368. $valid = ($valid && $model->{$join}->validator()->validates($options));
  369. }
  370. }
  371. return $valid;
  372. }
  373. /**
  374. * Propagates the beforeValidate event
  375. *
  376. * @param array $options
  377. * @return boolean
  378. */
  379. protected function _triggerBeforeValidate($options = array()) {
  380. $model = $this->getModel();
  381. $event = new CakeEvent('Model.beforeValidate', $model, array($options));
  382. list($event->break, $event->breakOn) = array(true, false);
  383. $model->getEventManager()->dispatch($event);
  384. if ($event->isStopped()) {
  385. return false;
  386. }
  387. return true;
  388. }
  389. }