ArrayContext.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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\View\Form;
  17. use Cake\Utility\Hash;
  18. /**
  19. * Provides a basic array based context provider for FormHelper.
  20. *
  21. * This adapter is useful in testing or when you have forms backed by
  22. * simple array data structures.
  23. *
  24. * Important keys:
  25. *
  26. * - `data` Holds the current values supplied for the fields.
  27. * - `defaults` The default values for fields. These values
  28. * will be used when there is no data set. Data should be nested following
  29. * the dot separated paths you access your fields with.
  30. * - `required` A nested array of fields, relationships and boolean
  31. * flags to indicate a field is required. The value can also be a string to be used
  32. * as the required error message
  33. * - `schema` An array of data that emulate the column structures that
  34. * Cake\Database\Schema\Schema uses. This array allows you to control
  35. * the inferred type for fields and allows auto generation of attributes
  36. * like maxlength, step and other HTML attributes. If you want
  37. * primary key/id detection to work. Make sure you have provided a `_constraints`
  38. * array that contains `primary`. See below for an example.
  39. * - `errors` An array of validation errors. Errors should be nested following
  40. * the dot separated paths you access your fields with.
  41. *
  42. * ### Example
  43. *
  44. * ```
  45. * $article = [
  46. * 'data' => [
  47. * 'id' => '1',
  48. * 'title' => 'First post!',
  49. * ],
  50. * 'schema' => [
  51. * 'id' => ['type' => 'integer'],
  52. * 'title' => ['type' => 'string', 'length' => 255],
  53. * '_constraints' => [
  54. * 'primary' => ['type' => 'primary', 'columns' => ['id']]
  55. * ]
  56. * ],
  57. * 'defaults' => [
  58. * 'title' => 'Default title',
  59. * ],
  60. * 'required' => [
  61. * 'id' => true, // will use default required message
  62. * 'title' => 'Please enter a title',
  63. * 'body' => false,
  64. * ],
  65. * ];
  66. * ```
  67. */
  68. class ArrayContext implements ContextInterface
  69. {
  70. /**
  71. * Context data for this object.
  72. *
  73. * @var array<string, mixed>
  74. */
  75. protected array $_context;
  76. /**
  77. * Constructor.
  78. *
  79. * @param array $context Context info.
  80. */
  81. public function __construct(array $context)
  82. {
  83. $context += [
  84. 'data' => [],
  85. 'schema' => [],
  86. 'required' => [],
  87. 'defaults' => [],
  88. 'errors' => [],
  89. ];
  90. $this->_context = $context;
  91. }
  92. /**
  93. * Get the fields used in the context as a primary key.
  94. *
  95. * @return array<string>
  96. */
  97. public function getPrimaryKey(): array
  98. {
  99. if (
  100. empty($this->_context['schema']['_constraints']) ||
  101. !is_array($this->_context['schema']['_constraints'])
  102. ) {
  103. return [];
  104. }
  105. foreach ($this->_context['schema']['_constraints'] as $data) {
  106. if (isset($data['type']) && $data['type'] === 'primary') {
  107. return (array)($data['columns'] ?? []);
  108. }
  109. }
  110. return [];
  111. }
  112. /**
  113. * @inheritDoc
  114. */
  115. public function isPrimaryKey(string $field): bool
  116. {
  117. $primaryKey = $this->getPrimaryKey();
  118. return in_array($field, $primaryKey, true);
  119. }
  120. /**
  121. * Returns whether this form is for a create operation.
  122. *
  123. * For this method to return true, both the primary key constraint
  124. * must be defined in the 'schema' data, and the 'defaults' data must
  125. * contain a value for all fields in the key.
  126. *
  127. * @return bool
  128. */
  129. public function isCreate(): bool
  130. {
  131. $primary = $this->getPrimaryKey();
  132. foreach ($primary as $column) {
  133. if (!empty($this->_context['defaults'][$column])) {
  134. return false;
  135. }
  136. }
  137. return true;
  138. }
  139. /**
  140. * Get the current value for a given field.
  141. *
  142. * This method will coalesce the current data and the 'defaults' array.
  143. *
  144. * @param string $field A dot separated path to the field a value
  145. * is needed for.
  146. * @param array<string, mixed> $options Options:
  147. *
  148. * - `default`: Default value to return if no value found in data or
  149. * context record.
  150. * - `schemaDefault`: Boolean indicating whether default value from
  151. * context's schema should be used if it's not explicitly provided.
  152. * @return mixed
  153. */
  154. public function val(string $field, array $options = []): mixed
  155. {
  156. $options += [
  157. 'default' => null,
  158. 'schemaDefault' => true,
  159. ];
  160. if (Hash::check($this->_context['data'], $field)) {
  161. return Hash::get($this->_context['data'], $field);
  162. }
  163. if ($options['default'] !== null || !$options['schemaDefault']) {
  164. return $options['default'];
  165. }
  166. if (empty($this->_context['defaults']) || !is_array($this->_context['defaults'])) {
  167. return null;
  168. }
  169. // Using Hash::check here incase the default value is actually null
  170. if (Hash::check($this->_context['defaults'], $field)) {
  171. return Hash::get($this->_context['defaults'], $field);
  172. }
  173. return Hash::get($this->_context['defaults'], $this->stripNesting($field));
  174. }
  175. /**
  176. * Check if a given field is 'required'.
  177. *
  178. * In this context class, this is simply defined by the 'required' array.
  179. *
  180. * @param string $field A dot separated path to check required-ness for.
  181. * @return bool|null
  182. */
  183. public function isRequired(string $field): ?bool
  184. {
  185. if (!is_array($this->_context['required'])) {
  186. return null;
  187. }
  188. $required = Hash::get($this->_context['required'], $field)
  189. ?? Hash::get($this->_context['required'], $this->stripNesting($field));
  190. if (!empty($required) || $required === '0') {
  191. return true;
  192. }
  193. return $required;
  194. }
  195. /**
  196. * @inheritDoc
  197. */
  198. public function getRequiredMessage(string $field): ?string
  199. {
  200. if (!is_array($this->_context['required'])) {
  201. return null;
  202. }
  203. $required = Hash::get($this->_context['required'], $field)
  204. ?? Hash::get($this->_context['required'], $this->stripNesting($field));
  205. if ($required === false) {
  206. return null;
  207. }
  208. if ($required === true) {
  209. $required = __d('cake', 'This field cannot be left empty');
  210. }
  211. return $required;
  212. }
  213. /**
  214. * Get field length from validation
  215. *
  216. * In this context class, this is simply defined by the 'length' array.
  217. *
  218. * @param string $field A dot separated path to check required-ness for.
  219. * @return int|null
  220. */
  221. public function getMaxLength(string $field): ?int
  222. {
  223. if (!is_array($this->_context['schema'])) {
  224. return null;
  225. }
  226. return Hash::get($this->_context['schema'], "$field.length");
  227. }
  228. /**
  229. * @inheritDoc
  230. */
  231. public function fieldNames(): array
  232. {
  233. $schema = $this->_context['schema'];
  234. unset($schema['_constraints'], $schema['_indexes']);
  235. /** @psalm-var list<string> */
  236. return array_keys($schema);
  237. }
  238. /**
  239. * Get the abstract field type for a given field name.
  240. *
  241. * @param string $field A dot separated path to get a schema type for.
  242. * @return string|null An abstract data type or null.
  243. * @see \Cake\Database\TypeFactory
  244. */
  245. public function type(string $field): ?string
  246. {
  247. if (!is_array($this->_context['schema'])) {
  248. return null;
  249. }
  250. $schema = Hash::get($this->_context['schema'], $field)
  251. ?? Hash::get($this->_context['schema'], $this->stripNesting($field));
  252. return $schema['type'] ?? null;
  253. }
  254. /**
  255. * Get an associative array of other attributes for a field name.
  256. *
  257. * @param string $field A dot separated path to get additional data on.
  258. * @return array An array of data describing the additional attributes on a field.
  259. */
  260. public function attributes(string $field): array
  261. {
  262. if (!is_array($this->_context['schema'])) {
  263. return [];
  264. }
  265. $schema = Hash::get($this->_context['schema'], $field)
  266. ?? Hash::get($this->_context['schema'], $this->stripNesting($field));
  267. return array_intersect_key(
  268. (array)$schema,
  269. array_flip(static::VALID_ATTRIBUTES)
  270. );
  271. }
  272. /**
  273. * Check whether a field has an error attached to it
  274. *
  275. * @param string $field A dot separated path to check errors on.
  276. * @return bool Returns true if the errors for the field are not empty.
  277. */
  278. public function hasError(string $field): bool
  279. {
  280. if (empty($this->_context['errors'])) {
  281. return false;
  282. }
  283. return Hash::check($this->_context['errors'], $field);
  284. }
  285. /**
  286. * Get the errors for a given field
  287. *
  288. * @param string $field A dot separated path to check errors on.
  289. * @return array An array of errors, an empty array will be returned when the
  290. * context has no errors.
  291. */
  292. public function error(string $field): array
  293. {
  294. if (empty($this->_context['errors'])) {
  295. return [];
  296. }
  297. return (array)Hash::get($this->_context['errors'], $field);
  298. }
  299. /**
  300. * Strips out any numeric nesting
  301. *
  302. * For example users.0.age will output as users.age
  303. *
  304. * @param string $field A dot separated path
  305. * @return string A string with stripped numeric nesting
  306. */
  307. protected function stripNesting(string $field): string
  308. {
  309. return preg_replace('/\.\d*\./', '.', $field);
  310. }
  311. }