RulesChecker.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\ORM;
  16. use Cake\Datasource\EntityInterface;
  17. use Cake\ORM\Rule\ExistsIn;
  18. use Cake\ORM\Rule\IsUnique;
  19. use InvalidArgumentException;
  20. /**
  21. * Contains logic for storing and checking rules on entities
  22. *
  23. * RulesCheckers are used by Table classes to ensure that the
  24. * current entity state satifies the application logic and business rules.
  25. *
  26. * RulesCheckers afford different rules to be applied in the create and update
  27. * scenario.
  28. *
  29. * ### Adding rules
  30. *
  31. * Rules must be callable objects that return true/false depending on whether or
  32. * not the rule has been satisified. You can use RulesChecker::add(), RulesChecker::addCreate(),
  33. * RulesChecker::addUpdate() and RulesChecker::addDelete to add rules to a checker.
  34. *
  35. * ### Running checks
  36. *
  37. * Generally a Table object will invoke the rules objects, but you can manually
  38. * invoke the checks by calling RulesChecker::checkCreate(), RulesChecker::checkUpdate() or
  39. * RulesChecker::checkDelete().
  40. */
  41. class RulesChecker {
  42. /**
  43. * Indicates that the checking rules to apply are those used for creating entities
  44. *
  45. * @var string
  46. */
  47. const CREATE = 'create';
  48. /**
  49. * Indicates that the checking rules to apply are those used for updating entities
  50. *
  51. * @var string
  52. */
  53. const UPDATE = 'update';
  54. /**
  55. * Indicates that the checking rules to apply are those used for deleting entities
  56. *
  57. * @var string
  58. */
  59. const DELETE = 'delete';
  60. /**
  61. * The list of rules to be checked on both create and update operations
  62. *
  63. * @var array
  64. */
  65. protected $_rules = [];
  66. /**
  67. * The list of rules to check during create operations
  68. *
  69. * @var array
  70. */
  71. protected $_createRules = [];
  72. /**
  73. * The list of rules to check during update operations
  74. *
  75. * @var array
  76. */
  77. protected $_updateRules = [];
  78. /**
  79. * The list of rules to check during delete operations
  80. *
  81. * @var array
  82. */
  83. protected $_deleteRules = [];
  84. /**
  85. * List of options to pass to every callable rule
  86. *
  87. * @var array
  88. */
  89. protected $_options = [];
  90. /**
  91. * Constructor. Takes the options to be passed to all rules.
  92. *
  93. * @param array $options The options to pass to every rule
  94. */
  95. public function __construct(array $options) {
  96. $this->_options = $options;
  97. }
  98. /**
  99. * Adds a rule that will be applied to the entity both on create and update
  100. * operations.
  101. *
  102. * ### Options
  103. *
  104. * The options array accept the following special keys:
  105. *
  106. * - `errorField`: The name of the entity field that will be marked as invalid
  107. * if the rule does not pass.
  108. * - `message`: The error message to set to `errorField` if the rule does not pass.
  109. *
  110. * @param callable $rule A callable function or object that will return whether
  111. * the entity is valid or not.
  112. * @param array $options List of extra options to pass to the rule callable as
  113. * second argument.
  114. * @return $this
  115. */
  116. public function add(callable $rule, array $options = []) {
  117. $this->_rules[] = $this->_addError($rule, $options);
  118. return $this;
  119. }
  120. /**
  121. * Adds a rule that will be applied to the entity on create operations.
  122. *
  123. * ### Options
  124. *
  125. * The options array accept the following special keys:
  126. *
  127. * - `errorField`: The name of the entity field that will be marked as invalid
  128. * if the rule does not pass.
  129. * - `message`: The error message to set to `errorField` if the rule does not pass.
  130. *
  131. * @param callable $rule A callable function or object that will return whether
  132. * the entity is valid or not.
  133. * @param array $options List of extra options to pass to the rule callable as
  134. * second argument.
  135. * @return $this
  136. */
  137. public function addCreate(callable $rule, array $options = []) {
  138. $this->_createRules[] = $this->_addError($rule, $options);
  139. return $this;
  140. }
  141. /**
  142. * Adds a rule that will be applied to the entity on update operations.
  143. *
  144. * ### Options
  145. *
  146. * The options array accept the following special keys:
  147. *
  148. * - `errorField`: The name of the entity field that will be marked as invalid
  149. * if the rule does not pass.
  150. * - `message`: The error message to set to `errorField` if the rule does not pass.
  151. *
  152. * @param callable $rule A callable function or object that will return whether
  153. * the entity is valid or not.
  154. * @param array $options List of extra options to pass to the rule callable as
  155. * second argument.
  156. * @return $this
  157. */
  158. public function addUpdate(callable $rule, array $options = []) {
  159. $this->_updateRules[] = $this->_addError($rule, $options);
  160. return $this;
  161. }
  162. /**
  163. * Adds a rule that will be applied to the entity on delete operations.
  164. *
  165. * ### Options
  166. *
  167. * The options array accept the following special keys:
  168. *
  169. * - `errorField`: The name of the entity field that will be marked as invalid
  170. * if the rule does not pass.
  171. * - `message`: The error message to set to `errorField` if the rule does not pass.
  172. *
  173. * @param callable $rule A callable function or object that will return whether
  174. * the entity is valid or not.
  175. * @param array $options List of extra options to pass to the rule callable as
  176. * second argument.
  177. * @return $this
  178. */
  179. public function addDelete(callable $rule, array $options = []) {
  180. $this->_deleteRules[] = $this->_addError($rule, $options);
  181. return $this;
  182. }
  183. /**
  184. * Runs each of the rules by passing the provided entity and returns true if all
  185. * of them pass. The rules to be applied are depended on the $mode parameter which
  186. * can only be RulesChecker::CREATE, RulesChecker::UPDATE or RulesChecker::DELETE
  187. *
  188. * @param \Cake\Datasource\EntityInterface $entity The entity to check for validity.
  189. * @return bool
  190. * @throws \InvalidArgumentException if an invalid mode is passed.
  191. */
  192. public function check(EntityInterface $entity, $mode) {
  193. if ($mode === self::CREATE) {
  194. return $this->checkCreate($entity);
  195. }
  196. if ($mode === self::UPDATE) {
  197. return $this->checkUpdate($entity);
  198. }
  199. if ($mode === self::DELETE) {
  200. return $this->checkDelete($entity);
  201. }
  202. throw new InvalidArgumentException('Wrong checking mode: ' . $mode);
  203. }
  204. /**
  205. * Runs each of the rules by passing the provided entity and returns true if all
  206. * of them pass. The rules selected will be only those specified to be run on 'create'
  207. *
  208. * @param \Cake\Datasource\EntityInterface $entity The entity to check for validity.
  209. * @return bool
  210. */
  211. public function checkCreate(EntityInterface $entity) {
  212. $success = true;
  213. foreach (array_merge($this->_rules, $this->_createRules) as $rule) {
  214. $success = $rule($entity, $this->_options) && $success;
  215. }
  216. return $success;
  217. }
  218. /**
  219. * Runs each of the rules by passing the provided entity and returns true if all
  220. * of them pass. The rules selected will be only those specified to be run on 'update'
  221. *
  222. * @param \Cake\Datasource\EntityInterface $entity The entity to check for validity.
  223. * @return bool
  224. */
  225. public function checkUpdate(EntityInterface $entity) {
  226. $success = true;
  227. foreach (array_merge($this->_rules, $this->_updateRules) as $rule) {
  228. $success = $rule($entity, $this->_options) && $success;
  229. }
  230. return $success;
  231. }
  232. /**
  233. * Runs each of the rules by passing the provided entity and returns true if all
  234. * of them pass. The rules selected will be only those specified to be run on 'delete'
  235. *
  236. * @param \Cake\Datasource\EntityInterface $entity The entity to check for validity.
  237. * @return bool
  238. */
  239. public function checkDelete(EntityInterface $entity) {
  240. $success = true;
  241. foreach ($this->_deleteRules as $rule) {
  242. $success = $rule($entity, $this->_options) && $success;
  243. }
  244. return $success;
  245. }
  246. /**
  247. * Returns a callable that can be used as a rule for checking the uniqueness of a value
  248. * in the table.
  249. *
  250. * ### Example:
  251. *
  252. * {{{
  253. * $rules->add($rules->isUnique('email', 'The email should be unique'));
  254. * }}}
  255. *
  256. * @param array $fields The list of fields to check for uniqueness.
  257. * @param string $message The error message to show in case the rule does not pass.
  258. * @return callable
  259. */
  260. public function isUnique(array $fields, $message = 'This value is already in use') {
  261. $errorField = current($fields);
  262. return $this->_addError(new IsUnique($fields), compact('errorField', 'message'));
  263. }
  264. /**
  265. * Returns a callable that can be used as a rule for checking that the values
  266. * extracted from the entity to check exist as the primary key in another table.
  267. *
  268. * This is useful for enforcing foreign key integrity checks.
  269. *
  270. * ### Example:
  271. *
  272. * {{{
  273. * $rules->add($rules->existsIn('author_id', 'Authors', 'Invalid Author'));
  274. *
  275. * $rules->add($rules->existsIn('site_id', new SitesTable(), 'Invalid Site'));
  276. * }}}
  277. *
  278. * @param string|array $field The field or list of fields to check for existence by
  279. * primary key lookup in the other table.
  280. * @param object|string $table The table name where the fields existence will be checked.
  281. * @param string $message The error message to show in case the rule does not pass.
  282. * @return callable
  283. */
  284. public function existsIn($field, $table, $message = 'This value does not exist') {
  285. $errorField = $field;
  286. return $this->_addError(new ExistsIn($field, $table), compact('errorField', 'message'));
  287. }
  288. /**
  289. * Utility method for decorating any callable so that if it returns false, the correct
  290. * property in the entity is marked as invalid.
  291. *
  292. * @param callable $rule The rule to decorate
  293. * @param array $options The options containing the error message and field
  294. * @return callable
  295. */
  296. protected function _addError($rule, $options) {
  297. return function ($entity, $scope) use ($rule, $options) {
  298. $pass = $rule($entity, $options + $scope);
  299. if ($pass || empty($options['errorField'])) {
  300. return $pass;
  301. }
  302. $message = isset($options['message']) ? $options['message'] : 'invalid';
  303. $entity->errors($options['errorField'], (array)$message);
  304. return $pass;
  305. };
  306. }
  307. }