Form.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Form;
  17. use Cake\Event\EventDispatcherInterface;
  18. use Cake\Event\EventDispatcherTrait;
  19. use Cake\Event\EventListenerInterface;
  20. use Cake\Event\EventManager;
  21. use Cake\Utility\Hash;
  22. use Cake\Validation\ValidatorAwareInterface;
  23. use Cake\Validation\ValidatorAwareTrait;
  24. /**
  25. * Form abstraction used to create forms not tied to ORM backed models,
  26. * or to other permanent datastores. Ideal for implementing forms on top of
  27. * API services, or contact forms.
  28. *
  29. * ### Building a form
  30. *
  31. * This class is most useful when subclassed. In a subclass you
  32. * should define the `_buildSchema`, `validationDefault` and optionally,
  33. * the `_execute` methods. These allow you to declare your form's
  34. * fields, validation and primary action respectively.
  35. *
  36. * Forms are conventionally placed in the `App\Form` namespace.
  37. */
  38. class Form implements EventListenerInterface, EventDispatcherInterface, ValidatorAwareInterface
  39. {
  40. use EventDispatcherTrait;
  41. use ValidatorAwareTrait;
  42. /**
  43. * Name of default validation set.
  44. *
  45. * @var string
  46. */
  47. public const DEFAULT_VALIDATOR = 'default';
  48. /**
  49. * The alias this object is assigned to validators as.
  50. *
  51. * @var string
  52. */
  53. public const VALIDATOR_PROVIDER_NAME = 'form';
  54. /**
  55. * The name of the event dispatched when a validator has been built.
  56. *
  57. * @var string
  58. */
  59. public const BUILD_VALIDATOR_EVENT = 'Form.buildValidator';
  60. /**
  61. * Schema class.
  62. *
  63. * @var string
  64. * @psalm-var class-string<\Cake\Form\Schema>
  65. */
  66. protected $_schemaClass = Schema::class;
  67. /**
  68. * The schema used by this form.
  69. *
  70. * @var \Cake\Form\Schema
  71. */
  72. protected $_schema;
  73. /**
  74. * The errors if any
  75. *
  76. * @var array
  77. */
  78. protected $_errors = [];
  79. /**
  80. * Form's data.
  81. *
  82. * @var array
  83. */
  84. protected $_data = [];
  85. /**
  86. * Constructor
  87. *
  88. * @param \Cake\Event\EventManager|null $eventManager The event manager.
  89. * Defaults to a new instance.
  90. */
  91. public function __construct(?EventManager $eventManager = null)
  92. {
  93. if ($eventManager !== null) {
  94. $this->setEventManager($eventManager);
  95. }
  96. $this->getEventManager()->on($this);
  97. if (method_exists($this, '_buildValidator')) {
  98. deprecationWarning(
  99. static::class . ' implements `_buildValidator` which is no longer used. ' .
  100. 'You should implement `buildValidator(Validator $validator, string $name): void` ' .
  101. 'or `validationDefault(Validator $validator): Validator` instead.'
  102. );
  103. }
  104. }
  105. /**
  106. * Get the Form callbacks this form is interested in.
  107. *
  108. * The conventional method map is:
  109. *
  110. * - Form.buildValidator => buildValidator
  111. *
  112. * @return array
  113. */
  114. public function implementedEvents(): array
  115. {
  116. if (method_exists($this, 'buildValidator')) {
  117. return [
  118. self::BUILD_VALIDATOR_EVENT => 'buildValidator',
  119. ];
  120. }
  121. return [];
  122. }
  123. /**
  124. * Get/Set the schema for this form.
  125. *
  126. * This method will call `_buildSchema()` when the schema
  127. * is first built. This hook method lets you configure the
  128. * schema or load a pre-defined one.
  129. *
  130. * @param \Cake\Form\Schema|null $schema The schema to set, or null.
  131. * @return \Cake\Form\Schema the schema instance.
  132. */
  133. public function schema(?Schema $schema = null): Schema
  134. {
  135. if ($schema === null && empty($this->_schema)) {
  136. $schema = $this->_buildSchema(new $this->_schemaClass());
  137. }
  138. if ($schema) {
  139. $this->_schema = $schema;
  140. }
  141. return $this->_schema;
  142. }
  143. /**
  144. * A hook method intended to be implemented by subclasses.
  145. *
  146. * You can use this method to define the schema using
  147. * the methods on Cake\Form\Schema, or loads a pre-defined
  148. * schema from a concrete class.
  149. *
  150. * @param \Cake\Form\Schema $schema The schema to customize.
  151. * @return \Cake\Form\Schema The schema to use.
  152. */
  153. protected function _buildSchema(Schema $schema): Schema
  154. {
  155. return $schema;
  156. }
  157. /**
  158. * Used to check if $data passes this form's validation.
  159. *
  160. * @param array $data The data to check.
  161. * @return bool Whether or not the data is valid.
  162. */
  163. public function validate(array $data): bool
  164. {
  165. $validator = $this->getValidator();
  166. $this->_errors = $validator->validate($data);
  167. return count($this->_errors) === 0;
  168. }
  169. /**
  170. * Get the errors in the form
  171. *
  172. * Will return the errors from the last call
  173. * to `validate()` or `execute()`.
  174. *
  175. * @return array Last set validation errors.
  176. */
  177. public function getErrors(): array
  178. {
  179. return $this->_errors;
  180. }
  181. /**
  182. * Set the errors in the form.
  183. *
  184. * ```
  185. * $errors = [
  186. * 'field_name' => ['rule_name' => 'message']
  187. * ];
  188. *
  189. * $form->setErrors($errors);
  190. * ```
  191. *
  192. * @param array $errors Errors list.
  193. * @return $this
  194. */
  195. public function setErrors(array $errors)
  196. {
  197. $this->_errors = $errors;
  198. return $this;
  199. }
  200. /**
  201. * Execute the form if it is valid.
  202. *
  203. * First validates the form, then calls the `_execute()` hook method.
  204. * This hook method can be implemented in subclasses to perform
  205. * the action of the form. This may be sending email, interacting
  206. * with a remote API, or anything else you may need.
  207. *
  208. * @param array $data Form data.
  209. * @return bool False on validation failure, otherwise returns the
  210. * result of the `_execute()` method.
  211. */
  212. public function execute(array $data): bool
  213. {
  214. if (!$this->validate($data)) {
  215. return false;
  216. }
  217. return $this->_execute($data);
  218. }
  219. /**
  220. * Hook method to be implemented in subclasses.
  221. *
  222. * Used by `execute()` to execute the form's action.
  223. *
  224. * @param array $data Form data.
  225. * @return bool
  226. */
  227. protected function _execute(array $data): bool
  228. {
  229. return true;
  230. }
  231. /**
  232. * Get field data.
  233. *
  234. * @param string|null $field The field name or null to get data array with
  235. * all fields.
  236. * @return mixed
  237. */
  238. public function getData(?string $field = null)
  239. {
  240. if ($field === null) {
  241. return $this->_data;
  242. }
  243. return Hash::get($this->_data, $field);
  244. }
  245. /**
  246. * Set form data.
  247. *
  248. * @param array $data Data array.
  249. * @return $this
  250. */
  251. public function setData(array $data)
  252. {
  253. $this->_data = $data;
  254. return $this;
  255. }
  256. /**
  257. * Get the printable version of a Form instance.
  258. *
  259. * @return array
  260. */
  261. public function __debugInfo(): array
  262. {
  263. $special = [
  264. '_schema' => $this->schema()->__debugInfo(),
  265. '_errors' => $this->getErrors(),
  266. '_validator' => $this->getValidator()->__debugInfo(),
  267. ];
  268. return $special + get_object_vars($this);
  269. }
  270. }