ArrayContext.php 10 KB

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