ArrayContext.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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\Http\ServerRequest;
  18. use Cake\Utility\Hash;
  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. * - `defaults` The default values for fields. These values
  28. * will be used when there is no request 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. * $data = [
  46. * 'schema' => [
  47. * 'id' => ['type' => 'integer'],
  48. * 'title' => ['type' => 'string', 'length' => 255],
  49. * '_constraints' => [
  50. * 'primary' => ['type' => 'primary', 'columns' => ['id']]
  51. * ]
  52. * ],
  53. * 'defaults' => [
  54. * 'id' => 1,
  55. * 'title' => 'First post!',
  56. * ],
  57. * 'required' => [
  58. * 'id' => true, // will use default required message
  59. * 'title' => 'Please enter a title',
  60. * 'body' => false,
  61. * ],
  62. * ];
  63. * ```
  64. */
  65. class ArrayContext implements ContextInterface
  66. {
  67. /**
  68. * The request object.
  69. *
  70. * @var \Cake\Http\ServerRequest
  71. */
  72. protected $_request;
  73. /**
  74. * Context data for this object.
  75. *
  76. * @var array
  77. */
  78. protected $_context;
  79. /**
  80. * Constructor.
  81. *
  82. * @param \Cake\Http\ServerRequest $request The request object.
  83. * @param array $context Context info.
  84. */
  85. public function __construct(ServerRequest $request, array $context)
  86. {
  87. $this->_request = $request;
  88. $context += [
  89. 'schema' => [],
  90. 'required' => [],
  91. 'defaults' => [],
  92. 'errors' => [],
  93. ];
  94. $this->_context = $context;
  95. }
  96. /**
  97. * Get the fields used in the context as a primary key.
  98. *
  99. * @return string[]
  100. * @deprecated 4.0.0 Renamed to getPrimaryKey()
  101. */
  102. public function primaryKey(): array
  103. {
  104. deprecationWarning('`ArrayContext::primaryKey()` is deprecated. Use `ArrayContext::getPrimaryKey()`.');
  105. return $this->getPrimaryKey();
  106. }
  107. /**
  108. * Get the fields used in the context as a primary key.
  109. *
  110. * @return string[]
  111. */
  112. public function getPrimaryKey(): array
  113. {
  114. if (
  115. empty($this->_context['schema']['_constraints']) ||
  116. !is_array($this->_context['schema']['_constraints'])
  117. ) {
  118. return [];
  119. }
  120. foreach ($this->_context['schema']['_constraints'] as $data) {
  121. if (isset($data['type']) && $data['type'] === 'primary') {
  122. return (array)($data['columns'] ?? []);
  123. }
  124. }
  125. return [];
  126. }
  127. /**
  128. * @inheritDoc
  129. */
  130. public function isPrimaryKey(string $field): bool
  131. {
  132. $primaryKey = $this->getPrimaryKey();
  133. return in_array($field, $primaryKey, true);
  134. }
  135. /**
  136. * Returns whether or not this form is for a create operation.
  137. *
  138. * For this method to return true, both the primary key constraint
  139. * must be defined in the 'schema' data, and the 'defaults' data must
  140. * contain a value for all fields in the key.
  141. *
  142. * @return bool
  143. */
  144. public function isCreate(): bool
  145. {
  146. $primary = $this->getPrimaryKey();
  147. foreach ($primary as $column) {
  148. if (!empty($this->_context['defaults'][$column])) {
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. /**
  155. * Get the current value for a given field.
  156. *
  157. * This method will coalesce the current request data and the 'defaults'
  158. * array.
  159. *
  160. * @param string $field A dot separated path to the field a value
  161. * is needed for.
  162. * @param array $options Options:
  163. *
  164. * - `default`: Default value to return if no value found in request
  165. * data or context record.
  166. * - `schemaDefault`: Boolean indicating whether default value from
  167. * context's schema should be used if it's not explicitly provided.
  168. *
  169. * @return mixed
  170. */
  171. public function val(string $field, array $options = [])
  172. {
  173. $options += [
  174. 'default' => null,
  175. 'schemaDefault' => true,
  176. ];
  177. $val = $this->_request->getData($field);
  178. if ($val !== null) {
  179. return $val;
  180. }
  181. if ($options['default'] !== null || !$options['schemaDefault']) {
  182. return $options['default'];
  183. }
  184. if (empty($this->_context['defaults']) || !is_array($this->_context['defaults'])) {
  185. return null;
  186. }
  187. // Using Hash::check here incase the default value is actually null
  188. if (Hash::check($this->_context['defaults'], $field)) {
  189. return Hash::get($this->_context['defaults'], $field);
  190. }
  191. return Hash::get($this->_context['defaults'], $this->stripNesting($field));
  192. }
  193. /**
  194. * Check if a given field is 'required'.
  195. *
  196. * In this context class, this is simply defined by the 'required' array.
  197. *
  198. * @param string $field A dot separated path to check required-ness for.
  199. * @return bool|null
  200. */
  201. public function isRequired(string $field): ?bool
  202. {
  203. if (!is_array($this->_context['required'])) {
  204. return null;
  205. }
  206. $required = Hash::get($this->_context['required'], $field);
  207. if ($required === null) {
  208. $required = Hash::get($this->_context['required'], $this->stripNesting($field));
  209. }
  210. if (!empty($required) || $required === '0') {
  211. return true;
  212. }
  213. return $required;
  214. }
  215. /**
  216. * @inheritDoc
  217. */
  218. public function getRequiredMessage(string $field): ?string
  219. {
  220. if (!is_array($this->_context['required'])) {
  221. return null;
  222. }
  223. $required = Hash::get($this->_context['required'], $field);
  224. if ($required === null) {
  225. $required = Hash::get($this->_context['required'], $this->stripNesting($field));
  226. }
  227. if ($required === false) {
  228. return null;
  229. }
  230. if ($required === true) {
  231. $required = __d('cake', 'This field cannot be left empty');
  232. }
  233. return $required;
  234. }
  235. /**
  236. * Get field length from validation
  237. *
  238. * In this context class, this is simply defined by the 'length' array.
  239. *
  240. * @param string $field A dot separated path to check required-ness for.
  241. * @return int|null
  242. */
  243. public function getMaxLength(string $field): ?int
  244. {
  245. if (!is_array($this->_context['schema'])) {
  246. return null;
  247. }
  248. return Hash::get($this->_context['schema'], "$field.length");
  249. }
  250. /**
  251. * @inheritDoc
  252. */
  253. public function fieldNames(): array
  254. {
  255. $schema = $this->_context['schema'];
  256. unset($schema['_constraints'], $schema['_indexes']);
  257. return array_keys($schema);
  258. }
  259. /**
  260. * Get the abstract field type for a given field name.
  261. *
  262. * @param string $field A dot separated path to get a schema type for.
  263. * @return string|null An abstract data type or null.
  264. * @see \Cake\Database\Type
  265. */
  266. public function type(string $field): ?string
  267. {
  268. if (!is_array($this->_context['schema'])) {
  269. return null;
  270. }
  271. $schema = Hash::get($this->_context['schema'], $field);
  272. if ($schema === null) {
  273. $schema = Hash::get($this->_context['schema'], $this->stripNesting($field));
  274. }
  275. return $schema['type'] ?? null;
  276. }
  277. /**
  278. * Get an associative array of other attributes for a field name.
  279. *
  280. * @param string $field A dot separated path to get additional data on.
  281. * @return array An array of data describing the additional attributes on a field.
  282. */
  283. public function attributes(string $field): array
  284. {
  285. if (!is_array($this->_context['schema'])) {
  286. return [];
  287. }
  288. $schema = Hash::get($this->_context['schema'], $field);
  289. if ($schema === null) {
  290. $schema = Hash::get($this->_context['schema'], $this->stripNesting($field));
  291. }
  292. $whitelist = ['length' => null, 'precision' => null];
  293. return array_intersect_key((array)$schema, $whitelist);
  294. }
  295. /**
  296. * Check whether or not a field has an error attached to it
  297. *
  298. * @param string $field A dot separated path to check errors on.
  299. * @return bool Returns true if the errors for the field are not empty.
  300. */
  301. public function hasError(string $field): bool
  302. {
  303. if (empty($this->_context['errors'])) {
  304. return false;
  305. }
  306. return Hash::check($this->_context['errors'], $field);
  307. }
  308. /**
  309. * Get the errors for a given field
  310. *
  311. * @param string $field A dot separated path to check errors on.
  312. * @return array An array of errors, an empty array will be returned when the
  313. * context has no errors.
  314. */
  315. public function error(string $field): array
  316. {
  317. if (empty($this->_context['errors'])) {
  318. return [];
  319. }
  320. return (array)Hash::get($this->_context['errors'], $field);
  321. }
  322. /**
  323. * Strips out any numeric nesting
  324. *
  325. * For example users.0.age will output as users.age
  326. *
  327. * @param string $field A dot separated path
  328. * @return string A string with stripped numeric nesting
  329. */
  330. protected function stripNesting(string $field): string
  331. {
  332. return preg_replace('/\.\d*\./', '.', $field);
  333. }
  334. }