Base for a static organization website

ModelValidator.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. <?php
  2. /**
  3. * ModelValidator.
  4. *
  5. * Provides the Model validation logic.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Model
  17. * @since CakePHP(tm) v 2.2.0
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('CakeValidationSet', 'Model/Validator');
  21. App::uses('Hash', 'Utility');
  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 whether 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 bool 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|bool 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('atomic' => true, 'deep' => false);
  120. $model->validationErrors = $validationErrors = $return = array();
  121. $model->create(null);
  122. $return[$model->alias] = true;
  123. if (!($model->set($data) && $model->validates($options))) {
  124. $validationErrors[$model->alias] = $model->validationErrors;
  125. $return[$model->alias] = false;
  126. }
  127. $data = $model->data;
  128. if (!empty($options['deep']) && isset($data[$model->alias])) {
  129. $recordData = $data[$model->alias];
  130. unset($data[$model->alias]);
  131. $data += $recordData;
  132. }
  133. $associations = $model->getAssociated();
  134. foreach ($data as $association => &$values) {
  135. $validates = true;
  136. if (isset($associations[$association])) {
  137. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  138. if ($options['deep']) {
  139. $validates = $model->{$association}->validateAssociated($values, $options);
  140. } else {
  141. $model->{$association}->create(null);
  142. $validates = $model->{$association}->set($values) && $model->{$association}->validates($options);
  143. $data[$association] = $model->{$association}->data[$model->{$association}->alias];
  144. }
  145. if (is_array($validates)) {
  146. $validates = !in_array(false, Hash::flatten($validates), true);
  147. }
  148. $return[$association] = $validates;
  149. } elseif ($associations[$association] === 'hasMany') {
  150. $validates = $model->{$association}->validateMany($values, $options);
  151. $return[$association] = $validates;
  152. }
  153. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  154. $validationErrors[$association] = $model->{$association}->validationErrors;
  155. }
  156. }
  157. }
  158. $model->validationErrors = $validationErrors;
  159. if (isset($validationErrors[$model->alias])) {
  160. $model->validationErrors = $validationErrors[$model->alias];
  161. unset($validationErrors[$model->alias]);
  162. $model->validationErrors = array_merge($model->validationErrors, $validationErrors);
  163. }
  164. if (!$options['atomic']) {
  165. return $return;
  166. }
  167. if ($return[$model->alias] === false || !empty($model->validationErrors)) {
  168. return false;
  169. }
  170. return true;
  171. }
  172. /**
  173. * Validates multiple individual records for a single model
  174. *
  175. * #### Options
  176. *
  177. * - atomic: If true (default), returns boolean. If false returns array.
  178. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  179. * - deep: If set to true, all associated data will be validated as well.
  180. *
  181. * Warning: This method could potentially change the passed argument `$data`,
  182. * If you do not want this to happen, make a copy of `$data` before passing it
  183. * to this method
  184. *
  185. * @param array &$data Record data to validate. This should be a numerically-indexed array
  186. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  187. * @return mixed If atomic: True on success, or false on failure.
  188. * Otherwise: array similar to the $data array passed, but values are set to true/false
  189. * depending on whether each record validated successfully.
  190. */
  191. public function validateMany(&$data, $options = array()) {
  192. $model = $this->getModel();
  193. $options += array('atomic' => true, 'deep' => false);
  194. $model->validationErrors = $validationErrors = $return = array();
  195. foreach ($data as $key => &$record) {
  196. if ($options['deep']) {
  197. $validates = $model->validateAssociated($record, $options);
  198. } else {
  199. $model->create(null);
  200. $validates = $model->set($record) && $model->validates($options);
  201. $data[$key] = $model->data;
  202. }
  203. if ($validates === false || (is_array($validates) && in_array(false, Hash::flatten($validates), true))) {
  204. $validationErrors[$key] = $model->validationErrors;
  205. $validates = false;
  206. } else {
  207. $validates = true;
  208. }
  209. $return[$key] = $validates;
  210. }
  211. $model->validationErrors = $validationErrors;
  212. if (!$options['atomic']) {
  213. return $return;
  214. }
  215. return empty($model->validationErrors);
  216. }
  217. /**
  218. * Returns an array of fields that have failed validation. On the current model. This method will
  219. * actually run validation rules over data, not just return the messages.
  220. *
  221. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  222. * @return array Array of invalid fields
  223. * @triggers Model.afterValidate $model
  224. * @see ModelValidator::validates()
  225. */
  226. public function errors($options = array()) {
  227. if (!$this->_triggerBeforeValidate($options)) {
  228. return false;
  229. }
  230. $model = $this->getModel();
  231. if (!$this->_parseRules()) {
  232. return $model->validationErrors;
  233. }
  234. $fieldList = $model->whitelist;
  235. if (empty($fieldList) && !empty($options['fieldList'])) {
  236. if (!empty($options['fieldList'][$model->alias]) && is_array($options['fieldList'][$model->alias])) {
  237. $fieldList = $options['fieldList'][$model->alias];
  238. } else {
  239. $fieldList = $options['fieldList'];
  240. }
  241. }
  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|null
  297. */
  298. public function getField($name = null) {
  299. $this->_parseRules();
  300. if ($name !== null) {
  301. if (!empty($this->_fields[$name])) {
  302. return $this->_fields[$name];
  303. }
  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 bool 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 $this
  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 passed fieldList and returns the list of fields 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. if (empty($fieldList) || Hash::dimensions($fieldList) > 1) {
  361. return $this->_fields;
  362. }
  363. $validateList = array();
  364. $this->validationErrors = array();
  365. foreach ((array)$fieldList as $f) {
  366. if (!empty($this->_fields[$f])) {
  367. $validateList[$f] = $this->_fields[$f];
  368. }
  369. }
  370. return $validateList;
  371. }
  372. /**
  373. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  374. * set and data in the data set.
  375. *
  376. * @param array $options Array of options to use on Validation of with models
  377. * @return bool Failure of validation on with models.
  378. * @see Model::validates()
  379. */
  380. protected function _validateWithModels($options) {
  381. $valid = true;
  382. $model = $this->getModel();
  383. foreach ($model->hasAndBelongsToMany as $assoc => $association) {
  384. if (empty($association['with']) || !isset($model->data[$assoc])) {
  385. continue;
  386. }
  387. list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
  388. $data = $model->data[$assoc];
  389. $newData = array();
  390. foreach ((array)$data as $row) {
  391. if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  392. $newData[] = $row;
  393. } elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  394. $newData[] = $row[$join];
  395. }
  396. }
  397. foreach ($newData as $data) {
  398. $data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
  399. $model->{$join}->create($data);
  400. $valid = ($valid && $model->{$join}->validator()->validates($options));
  401. }
  402. }
  403. return $valid;
  404. }
  405. /**
  406. * Propagates beforeValidate event
  407. *
  408. * @param array $options Options to pass to callback.
  409. * @return bool
  410. * @triggers Model.beforeValidate $model, array($options)
  411. */
  412. protected function _triggerBeforeValidate($options = array()) {
  413. $model = $this->getModel();
  414. $event = new CakeEvent('Model.beforeValidate', $model, array($options));
  415. list($event->break, $event->breakOn) = array(true, false);
  416. $model->getEventManager()->dispatch($event);
  417. if ($event->isStopped()) {
  418. return false;
  419. }
  420. return true;
  421. }
  422. /**
  423. * Returns whether a rule set is defined for a field or not
  424. *
  425. * @param string $field name of the field to check
  426. * @return bool
  427. */
  428. public function offsetExists($field) {
  429. $this->_parseRules();
  430. return isset($this->_fields[$field]);
  431. }
  432. /**
  433. * Returns the rule set for a field
  434. *
  435. * @param string $field name of the field to check
  436. * @return CakeValidationSet
  437. */
  438. public function offsetGet($field) {
  439. $this->_parseRules();
  440. return $this->_fields[$field];
  441. }
  442. /**
  443. * Sets the rule set for a field
  444. *
  445. * @param string $field name of the field to set
  446. * @param array|CakeValidationSet $rules set of rules to apply to field
  447. * @return void
  448. */
  449. public function offsetSet($field, $rules) {
  450. $this->_parseRules();
  451. if (!$rules instanceof CakeValidationSet) {
  452. $rules = new CakeValidationSet($field, $rules);
  453. $methods = $this->getMethods();
  454. $rules->setMethods($methods);
  455. }
  456. $this->_fields[$field] = $rules;
  457. }
  458. /**
  459. * Unsets the rule set for a field
  460. *
  461. * @param string $field name of the field to unset
  462. * @return void
  463. */
  464. public function offsetUnset($field) {
  465. $this->_parseRules();
  466. unset($this->_fields[$field]);
  467. }
  468. /**
  469. * Returns an iterator for each of the fields to be validated
  470. *
  471. * @return ArrayIterator
  472. */
  473. public function getIterator() {
  474. $this->_parseRules();
  475. return new ArrayIterator($this->_fields);
  476. }
  477. /**
  478. * Returns the number of fields having validation rules
  479. *
  480. * @return int
  481. */
  482. public function count() {
  483. $this->_parseRules();
  484. return count($this->_fields);
  485. }
  486. /**
  487. * Adds a new rule to a field's rule set. If second argument is an array or instance of
  488. * CakeValidationSet then rules list for the field will be replaced with second argument and
  489. * third argument will be ignored.
  490. *
  491. * ## Example:
  492. *
  493. * ```
  494. * $validator
  495. * ->add('title', 'required', array('rule' => 'notBlank', 'required' => true))
  496. * ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
  497. *
  498. * $validator->add('password', array(
  499. * 'size' => array('rule' => array('lengthBetween', 8, 20)),
  500. * 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
  501. * ));
  502. * ```
  503. *
  504. * @param string $field The name of the field where the rule is to be added
  505. * @param string|array|CakeValidationSet $name name of the rule to be added or list of rules for the field
  506. * @param array|CakeValidationRule $rule or list of rules to be added to the field's rule set
  507. * @return $this
  508. */
  509. public function add($field, $name, $rule = null) {
  510. $this->_parseRules();
  511. if ($name instanceof CakeValidationSet) {
  512. $this->_fields[$field] = $name;
  513. return $this;
  514. }
  515. if (!isset($this->_fields[$field])) {
  516. $rule = (is_string($name)) ? array($name => $rule) : $name;
  517. $this->_fields[$field] = new CakeValidationSet($field, $rule);
  518. } else {
  519. if (is_string($name)) {
  520. $this->_fields[$field]->setRule($name, $rule);
  521. } else {
  522. $this->_fields[$field]->setRules($name);
  523. }
  524. }
  525. $methods = $this->getMethods();
  526. $this->_fields[$field]->setMethods($methods);
  527. return $this;
  528. }
  529. /**
  530. * Removes a rule from the set by its name
  531. *
  532. * ## Example:
  533. *
  534. * ```
  535. * $validator
  536. * ->remove('title', 'required')
  537. * ->remove('user_id')
  538. * ```
  539. *
  540. * @param string $field The name of the field from which the rule will be removed
  541. * @param string $rule the name of the rule to be removed
  542. * @return $this
  543. */
  544. public function remove($field, $rule = null) {
  545. $this->_parseRules();
  546. if ($rule === null) {
  547. unset($this->_fields[$field]);
  548. } else {
  549. $this->_fields[$field]->removeRule($rule);
  550. }
  551. return $this;
  552. }
  553. }