Form.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. * Set the schema for this form.
  125. *
  126. * @since 4.1.0
  127. * @param \Cake\Form\Schema $schema The schema to set
  128. * @return $this
  129. */
  130. public function setSchema(Schema $schema)
  131. {
  132. $this->_schema = $schema;
  133. return $this;
  134. }
  135. /**
  136. * Get the schema for this form.
  137. *
  138. * This method will call `_buildSchema()` when the schema
  139. * is first built. This hook method lets you configure the
  140. * schema or load a pre-defined one.
  141. *
  142. * @since 4.1.0
  143. * @return \Cake\Form\Schema the schema instance.
  144. */
  145. public function getSchema(): Schema
  146. {
  147. if ($this->_schema === null) {
  148. $this->_schema = $this->_buildSchema(new $this->_schemaClass());
  149. }
  150. return $this->_schema;
  151. }
  152. /**
  153. * Get/Set the schema for this form.
  154. *
  155. * This method will call `_buildSchema()` when the schema
  156. * is first built. This hook method lets you configure the
  157. * schema or load a pre-defined one.
  158. *
  159. * @deprecated 4.1.0 Use {@link setSchema()}/{@link getSchema()} instead.
  160. * @param \Cake\Form\Schema|null $schema The schema to set, or null.
  161. * @return \Cake\Form\Schema the schema instance.
  162. */
  163. public function schema(?Schema $schema = null): Schema
  164. {
  165. deprecationWarning('Form::schema() is deprecated. Use setSchema() and getSchema() instead.');
  166. if ($schema !== null) {
  167. $this->setSchema($schema);
  168. }
  169. return $this->getSchema();
  170. }
  171. /**
  172. * A hook method intended to be implemented by subclasses.
  173. *
  174. * You can use this method to define the schema using
  175. * the methods on Cake\Form\Schema, or loads a pre-defined
  176. * schema from a concrete class.
  177. *
  178. * @param \Cake\Form\Schema $schema The schema to customize.
  179. * @return \Cake\Form\Schema The schema to use.
  180. */
  181. protected function _buildSchema(Schema $schema): Schema
  182. {
  183. return $schema;
  184. }
  185. /**
  186. * Used to check if $data passes this form's validation.
  187. *
  188. * @param array $data The data to check.
  189. * @return bool Whether or not the data is valid.
  190. */
  191. public function validate(array $data): bool
  192. {
  193. $validator = $this->getValidator();
  194. $this->_errors = $validator->validate($data);
  195. return count($this->_errors) === 0;
  196. }
  197. /**
  198. * Get the errors in the form
  199. *
  200. * Will return the errors from the last call
  201. * to `validate()` or `execute()`.
  202. *
  203. * @return array Last set validation errors.
  204. */
  205. public function getErrors(): array
  206. {
  207. return $this->_errors;
  208. }
  209. /**
  210. * Set the errors in the form.
  211. *
  212. * ```
  213. * $errors = [
  214. * 'field_name' => ['rule_name' => 'message']
  215. * ];
  216. *
  217. * $form->setErrors($errors);
  218. * ```
  219. *
  220. * @param array $errors Errors list.
  221. * @return $this
  222. */
  223. public function setErrors(array $errors)
  224. {
  225. $this->_errors = $errors;
  226. return $this;
  227. }
  228. /**
  229. * Execute the form if it is valid.
  230. *
  231. * First validates the form, then calls the `_execute()` hook method.
  232. * This hook method can be implemented in subclasses to perform
  233. * the action of the form. This may be sending email, interacting
  234. * with a remote API, or anything else you may need.
  235. *
  236. * @param array $data Form data.
  237. * @return bool False on validation failure, otherwise returns the
  238. * result of the `_execute()` method.
  239. */
  240. public function execute(array $data): bool
  241. {
  242. $this->_data = $data;
  243. if (!$this->validate($data)) {
  244. return false;
  245. }
  246. return $this->_execute($data);
  247. }
  248. /**
  249. * Hook method to be implemented in subclasses.
  250. *
  251. * Used by `execute()` to execute the form's action.
  252. *
  253. * @param array $data Form data.
  254. * @return bool
  255. */
  256. protected function _execute(array $data): bool
  257. {
  258. return true;
  259. }
  260. /**
  261. * Get field data.
  262. *
  263. * @param string|null $field The field name or null to get data array with
  264. * all fields.
  265. * @return mixed
  266. */
  267. public function getData(?string $field = null)
  268. {
  269. if ($field === null) {
  270. return $this->_data;
  271. }
  272. return Hash::get($this->_data, $field);
  273. }
  274. /**
  275. * Saves a variable or an associative array of variables for use inside form data.
  276. *
  277. * @param string|array $name The key to write, can be a dot notation value.
  278. * Alternatively can be an array containing key(s) and value(s).
  279. * @param mixed $value Value to set for var
  280. * @return $this
  281. */
  282. public function set($name, $value = null)
  283. {
  284. $write = $name;
  285. if (!is_array($name)) {
  286. $write = [$name => $value];
  287. }
  288. /** @psalm-suppress PossiblyInvalidIterator */
  289. foreach ($write as $key => $val) {
  290. $this->_data = Hash::insert($this->_data, $key, $val);
  291. }
  292. return $this;
  293. }
  294. /**
  295. * Set form data.
  296. *
  297. * @param array $data Data array.
  298. * @return $this
  299. */
  300. public function setData(array $data)
  301. {
  302. $this->_data = $data;
  303. return $this;
  304. }
  305. /**
  306. * Get the printable version of a Form instance.
  307. *
  308. * @return array
  309. */
  310. public function __debugInfo(): array
  311. {
  312. $special = [
  313. '_schema' => $this->getSchema()->__debugInfo(),
  314. '_errors' => $this->getErrors(),
  315. '_validator' => $this->getValidator()->__debugInfo(),
  316. ];
  317. return $special + get_object_vars($this);
  318. }
  319. }