1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 3.0.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\View\Form;
16:
17: use Cake\Http\ServerRequest;
18: use Cake\Utility\Hash;
19: use Cake\Validation\Validator;
20:
21: /**
22: * Provides a basic array based context provider for FormHelper.
23: *
24: * This adapter is useful in testing or when you have forms backed by
25: * simple array data structures.
26: *
27: * Important keys:
28: *
29: * - `defaults` The default values for fields. These values
30: * will be used when there is no request data set. Data should be nested following
31: * the dot separated paths you access your fields with.
32: * - `required` A nested array of fields, relationships and boolean
33: * flags to indicate a field is required. The value can also be a string to be used
34: * as the required error message
35: * - `schema` An array of data that emulate the column structures that
36: * Cake\Database\Schema\Schema uses. This array allows you to control
37: * the inferred type for fields and allows auto generation of attributes
38: * like maxlength, step and other HTML attributes. If you want
39: * primary key/id detection to work. Make sure you have provided a `_constraints`
40: * array that contains `primary`. See below for an example.
41: * - `errors` An array of validation errors. Errors should be nested following
42: * the dot separated paths you access your fields with.
43: *
44: * ### Example
45: *
46: * ```
47: * $data = [
48: * 'schema' => [
49: * 'id' => ['type' => 'integer'],
50: * 'title' => ['type' => 'string', 'length' => 255],
51: * '_constraints' => [
52: * 'primary' => ['type' => 'primary', 'columns' => ['id']]
53: * ]
54: * ],
55: * 'defaults' => [
56: * 'id' => 1,
57: * 'title' => 'First post!',
58: * ],
59: * 'required' => [
60: * 'id' => true, // will use default required message
61: * 'title' => 'Please enter a title',
62: * 'body' => false,
63: * ],
64: * ];
65: * ```
66: */
67: class ArrayContext implements ContextInterface
68: {
69:
70: /**
71: * The request object.
72: *
73: * @var \Cake\Http\ServerRequest
74: */
75: protected $_request;
76:
77: /**
78: * Context data for this object.
79: *
80: * @var array
81: */
82: protected $_context;
83:
84: /**
85: * Constructor.
86: *
87: * @param \Cake\Http\ServerRequest $request The request object.
88: * @param array $context Context info.
89: */
90: public function __construct(ServerRequest $request, array $context)
91: {
92: $this->_request = $request;
93: $context += [
94: 'schema' => [],
95: 'required' => [],
96: 'defaults' => [],
97: 'errors' => [],
98: ];
99: $this->_context = $context;
100: }
101:
102: /**
103: * Get the fields used in the context as a primary key.
104: *
105: * @return array
106: */
107: public function primaryKey()
108: {
109: if (empty($this->_context['schema']['_constraints']) ||
110: !is_array($this->_context['schema']['_constraints'])
111: ) {
112: return [];
113: }
114: foreach ($this->_context['schema']['_constraints'] as $data) {
115: if (isset($data['type']) && $data['type'] === 'primary') {
116: return isset($data['columns']) ? (array)$data['columns'] : [];
117: }
118: }
119:
120: return [];
121: }
122:
123: /**
124: * {@inheritDoc}
125: */
126: public function isPrimaryKey($field)
127: {
128: $primaryKey = $this->primaryKey();
129:
130: return in_array($field, $primaryKey);
131: }
132:
133: /**
134: * Returns whether or not this form is for a create operation.
135: *
136: * For this method to return true, both the primary key constraint
137: * must be defined in the 'schema' data, and the 'defaults' data must
138: * contain a value for all fields in the key.
139: *
140: * @return bool
141: */
142: public function isCreate()
143: {
144: $primary = $this->primaryKey();
145: foreach ($primary as $column) {
146: if (!empty($this->_context['defaults'][$column])) {
147: return false;
148: }
149: }
150:
151: return true;
152: }
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: * - `default`: Default value to return if no value found in request
164: * data or context record.
165: * - `schemaDefault`: Boolean indicating whether default value from
166: * context's schema should be used if it's not explicitly provided.
167: * @return mixed
168: */
169: public function val($field, $options = [])
170: {
171: $options += [
172: 'default' => null,
173: 'schemaDefault' => true
174: ];
175:
176: $val = $this->_request->getData($field);
177: if ($val !== null) {
178: return $val;
179: }
180: if ($options['default'] !== null || !$options['schemaDefault']) {
181: return $options['default'];
182: }
183: if (empty($this->_context['defaults']) || !is_array($this->_context['defaults'])) {
184: return null;
185: }
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:
192: return Hash::get($this->_context['defaults'], $this->stripNesting($field));
193: }
194:
195: /**
196: * Check if a given field is 'required'.
197: *
198: * In this context class, this is simply defined by the 'required' array.
199: *
200: * @param string $field A dot separated path to check required-ness for.
201: * @return bool
202: */
203: public function isRequired($field)
204: {
205: return (bool)$this->getRequiredMessage($field);
206: }
207:
208: /**
209: * {@inheritDoc}
210: */
211: public function getRequiredMessage($field)
212: {
213: if (!is_array($this->_context['required'])) {
214: return null;
215: }
216: $required = Hash::get($this->_context['required'], $field);
217: if ($required === null) {
218: $required = Hash::get($this->_context['required'], $this->stripNesting($field));
219: }
220:
221: if ($required === false) {
222: return null;
223: }
224:
225: if ($required === true) {
226: $required = __d('cake', 'This field is required');
227: }
228:
229: return $required;
230: }
231:
232: /**
233: * Get field length from validation
234: *
235: * In this context class, this is simply defined by the 'length' array.
236: *
237: * @param string $field A dot separated path to check required-ness for.
238: * @return int|null
239: */
240: public function getMaxLength($field)
241: {
242: if (!is_array($this->_context['schema'])) {
243: return null;
244: }
245:
246: return Hash::get($this->_context['schema'], "$field.length");
247: }
248:
249: /**
250: * {@inheritDoc}
251: */
252: public function fieldNames()
253: {
254: $schema = $this->_context['schema'];
255: unset($schema['_constraints'], $schema['_indexes']);
256:
257: return array_keys($schema);
258: }
259:
260: /**
261: * Get the abstract field type for a given field name.
262: *
263: * @param string $field A dot separated path to get a schema type for.
264: * @return null|string An abstract data type or null.
265: * @see \Cake\Database\Type
266: */
267: public function type($field)
268: {
269: if (!is_array($this->_context['schema'])) {
270: return null;
271: }
272:
273: $schema = Hash::get($this->_context['schema'], $field);
274: if ($schema === null) {
275: $schema = Hash::get($this->_context['schema'], $this->stripNesting($field));
276: }
277:
278: return isset($schema['type']) ? $schema['type'] : null;
279: }
280:
281: /**
282: * Get an associative array of other attributes for a field name.
283: *
284: * @param string $field A dot separated path to get additional data on.
285: * @return array An array of data describing the additional attributes on a field.
286: */
287: public function attributes($field)
288: {
289: if (!is_array($this->_context['schema'])) {
290: return [];
291: }
292: $schema = Hash::get($this->_context['schema'], $field);
293: if ($schema === null) {
294: $schema = Hash::get($this->_context['schema'], $this->stripNesting($field));
295: }
296: $whitelist = ['length' => null, 'precision' => null];
297:
298: return array_intersect_key((array)$schema, $whitelist);
299: }
300:
301: /**
302: * Check whether or not a field has an error attached to it
303: *
304: * @param string $field A dot separated path to check errors on.
305: * @return bool Returns true if the errors for the field are not empty.
306: */
307: public function hasError($field)
308: {
309: if (empty($this->_context['errors'])) {
310: return false;
311: }
312:
313: return (bool)Hash::check($this->_context['errors'], $field);
314: }
315:
316: /**
317: * Get the errors for a given field
318: *
319: * @param string $field A dot separated path to check errors on.
320: * @return array An array of errors, an empty array will be returned when the
321: * context has no errors.
322: */
323: public function error($field)
324: {
325: if (empty($this->_context['errors'])) {
326: return [];
327: }
328:
329: return (array)Hash::get($this->_context['errors'], $field);
330: }
331:
332: /**
333: * Strips out any numeric nesting
334: *
335: * For example users.0.age will output as users.age
336: *
337: * @param string $field A dot separated path
338: * @return string A string with stripped numeric nesting
339: */
340: protected function stripNesting($field)
341: {
342: return preg_replace('/\.\d*\./', '.', $field);
343: }
344: }
345: