-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
EntityContext.php
750 lines (662 loc) · 22.6 KB
/
EntityContext.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Form;
use ArrayAccess;
use Cake\Collection\Collection;
use Cake\Core\Exception\CakeException;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\InvalidPropertyInterface;
use Cake\ORM\Entity;
use Cake\ORM\Locator\LocatorAwareTrait;
use Cake\ORM\Table;
use Cake\Utility\Inflector;
use Cake\Validation\Validator;
use InvalidArgumentException;
use Traversable;
use function Cake\Core\namespaceSplit;
/**
* Provides a form context around a single entity and its relations.
* It also can be used as context around an array or iterator of entities.
*
* This class lets FormHelper interface with entities or collections
* of entities.
*
* Important Keys:
*
* - `entity` The entity this context is operating on.
* - `table` Either the ORM\Table instance to fetch schema/validators
* from, an array of table instances in the case of a form spanning
* multiple entities, or the name(s) of the table.
* If this is null the table name(s) will be determined using naming
* conventions.
* - `validator` Either the Validation\Validator to use, or the name of the
* validation method to call on the table object. For example 'default'.
* Defaults to 'default'. Can be an array of table alias=>validators when
* dealing with associated forms.
*/
class EntityContext implements ContextInterface
{
use LocatorAwareTrait;
/**
* Context data for this object.
*
* @var array<string, mixed>
*/
protected array $_context;
/**
* The name of the top level entity/table object.
*
* @var string
*/
protected string $_rootName;
/**
* Boolean to track whether the entity is a
* collection.
*
* @var bool
*/
protected bool $_isCollection = false;
/**
* A dictionary of tables
*
* @var array<\Cake\ORM\Table>
*/
protected array $_tables = [];
/**
* Dictionary of validators.
*
* @var array<\Cake\Validation\Validator>
*/
protected array $_validator = [];
/**
* Constructor.
*
* @param array<string, mixed> $context Context info.
*/
public function __construct(array $context)
{
$context += [
'entity' => null,
'table' => null,
'validator' => [],
];
$this->_context = $context;
$this->_prepare();
}
/**
* Prepare some additional data from the context.
*
* If the table option was provided to the constructor and it
* was a string, TableLocator will be used to get the correct table instance.
*
* If an object is provided as the table option, it will be used as is.
*
* If no table option is provided, the table name will be derived based on
* naming conventions. This inference will work with a number of common objects
* like arrays, Collection objects and ResultSets.
*
* @return void
* @throws \Cake\Core\Exception\CakeException When a table object cannot be located/inferred.
*/
protected function _prepare(): void
{
$table = $this->_context['table'];
/** @var \Cake\Datasource\EntityInterface|iterable<\Cake\Datasource\EntityInterface|array> $entity */
$entity = $this->_context['entity'];
$this->_isCollection = is_iterable($entity);
if (!$table) {
if ($this->_isCollection) {
/** @var iterable<\Cake\Datasource\EntityInterface|array> $entity */
foreach ($entity as $e) {
$entity = $e;
break;
}
}
if ($entity instanceof EntityInterface) {
$table = $entity->getSource();
}
if (!$table && $entity instanceof EntityInterface && $entity::class !== Entity::class) {
[, $entityClass] = namespaceSplit($entity::class);
$table = Inflector::pluralize($entityClass);
}
}
if (is_string($table) && $table !== '') {
$table = $this->getTableLocator()->get($table);
}
if (!($table instanceof Table)) {
throw new CakeException('Unable to find table class for current entity.');
}
$alias = $this->_rootName = $table->getAlias();
$this->_tables[$alias] = $table;
}
/**
* Get the primary key data for the context.
*
* Gets the primary key columns from the root entity's schema.
*
* @return array<string>
*/
public function getPrimaryKey(): array
{
return (array)$this->_tables[$this->_rootName]->getPrimaryKey();
}
/**
* @inheritDoc
*/
public function isPrimaryKey(string $field): bool
{
$parts = explode('.', $field);
$table = $this->_getTable($parts);
if (!$table) {
return false;
}
$primaryKey = (array)$table->getPrimaryKey();
return in_array(array_pop($parts), $primaryKey, true);
}
/**
* Check whether this form is a create or update.
*
* If the context is for a single entity, the entity's isNew() method will
* be used. If isNew() returns null, a create operation will be assumed.
*
* If the context is for a collection or array the first object in the
* collection will be used.
*
* @return bool
*/
public function isCreate(): bool
{
$entity = $this->_context['entity'];
if (is_iterable($entity)) {
foreach ($entity as $e) {
$entity = $e;
break;
}
}
if ($entity instanceof EntityInterface) {
return $entity->isNew() !== false;
}
return true;
}
/**
* Get the value for a given path.
*
* Traverses the entity data and finds the value for $path.
*
* @param string $field The dot separated path to the value.
* @param array<string, mixed> $options Options:
*
* - `default`: Default value to return if no value found in data or
* entity.
* - `schemaDefault`: Boolean indicating whether default value from table
* schema should be used if it's not explicitly provided.
* @return mixed The value of the field or null on a miss.
*/
public function val(string $field, array $options = []): mixed
{
$options += [
'default' => null,
'schemaDefault' => true,
];
if (empty($this->_context['entity'])) {
return $options['default'];
}
$parts = explode('.', $field);
$entity = $this->entity($parts);
if ($entity && end($parts) === '_ids') {
return $this->_extractMultiple($entity, $parts);
}
if ($entity instanceof EntityInterface) {
$part = end($parts);
if ($entity instanceof InvalidPropertyInterface) {
$val = $entity->getInvalidField($part);
if ($val !== null) {
return $val;
}
}
$val = $entity->get($part);
if ($val !== null) {
return $val;
}
if (
$options['default'] !== null
|| !$options['schemaDefault']
|| !$entity->isNew()
) {
return $options['default'];
}
return $this->_schemaDefault($parts);
}
if (is_array($entity) || $entity instanceof ArrayAccess) {
$key = array_pop($parts);
return $entity[$key] ?? $options['default'];
}
return null;
}
/**
* Get default value from table schema for given entity field.
*
* @param array<string> $parts Each one of the parts in a path for a field name
* @return mixed
*/
protected function _schemaDefault(array $parts): mixed
{
$table = $this->_getTable($parts);
if ($table === null) {
return null;
}
$field = end($parts);
$defaults = $table->getSchema()->defaultValues();
if ($field === false || !array_key_exists($field, $defaults)) {
return null;
}
return $defaults[$field];
}
/**
* Helper method used to extract all the primary key values out of an array, The
* primary key column is guessed out of the provided $path array
*
* @param mixed $values The list from which to extract primary keys from
* @param array<string> $path Each one of the parts in a path for a field name
* @return array|null
*/
protected function _extractMultiple(mixed $values, array $path): ?array
{
if (!is_iterable($values)) {
return null;
}
$table = $this->_getTable($path, false);
$primary = $table ? (array)$table->getPrimaryKey() : ['id'];
return (new Collection($values))->extract($primary[0])->toArray();
}
/**
* Fetch the entity or data value for a given path
*
* This method will traverse the given path and find the entity
* or array value for a given path.
*
* If you only want the terminal Entity for a path use `leafEntity` instead.
*
* @param array<string>|null $path Each one of the parts in a path for a field name
* or null to get the entity passed in constructor context.
* @return \Cake\Datasource\EntityInterface|iterable|null
* @throws \Cake\Core\Exception\CakeException When properties cannot be read.
*/
public function entity(?array $path = null): EntityInterface|iterable|null
{
if ($path === null) {
return $this->_context['entity'];
}
$oneElement = count($path) === 1;
if ($oneElement && $this->_isCollection) {
return null;
}
$entity = $this->_context['entity'];
if ($oneElement) {
return $entity;
}
if ($path[0] === $this->_rootName) {
$path = array_slice($path, 1);
}
$len = count($path);
$last = $len - 1;
for ($i = 0; $i < $len; $i++) {
$prop = $path[$i];
$next = $this->_getProp($entity, $prop);
$isLast = ($i === $last);
if (!$isLast && $next === null && $prop !== '_ids') {
$table = $this->_getTable($path);
if ($table) {
return $table->newEmptyEntity();
}
}
$isTraversable = (
is_iterable($next) ||
$next instanceof EntityInterface
);
if ($isLast || !$isTraversable) {
return $entity;
}
$entity = $next;
}
throw new CakeException(sprintf(
'Unable to fetch property `%s`.',
implode('.', $path)
));
}
/**
* Fetch the terminal or leaf entity for the given path.
*
* Traverse the path until an entity cannot be found. Lists containing
* entities will be traversed if the first element contains an entity.
* Otherwise, the containing Entity will be assumed to be the terminal one.
*
* @param array|null $path Each one of the parts in a path for a field name
* or null to get the entity passed in constructor context.
* @return array Containing the found entity, and remaining un-matched path.
* @throws \Cake\Core\Exception\CakeException When properties cannot be read.
*/
protected function leafEntity(?array $path = null): array
{
if ($path === null) {
return $this->_context['entity'];
}
$oneElement = count($path) === 1;
if ($oneElement && $this->_isCollection) {
throw new CakeException(sprintf(
'Unable to fetch property `%s`.',
implode('.', $path)
));
}
$entity = $this->_context['entity'];
if ($oneElement) {
return [$entity, $path];
}
if ($path[0] === $this->_rootName) {
$path = array_slice($path, 1);
}
$len = count($path);
$leafEntity = $entity;
for ($i = 0; $i < $len; $i++) {
$prop = $path[$i];
$next = $this->_getProp($entity, $prop);
// Did not dig into an entity, return the current one.
if (is_array($entity) && !($next instanceof EntityInterface || $next instanceof Traversable)) {
return [$leafEntity, array_slice($path, $i - 1)];
}
if ($next instanceof EntityInterface) {
$leafEntity = $next;
}
// If we are at the end of traversable elements
// return the last entity found.
$isTraversable = (
is_array($next) ||
$next instanceof Traversable ||
$next instanceof EntityInterface
);
if (!$isTraversable) {
return [$leafEntity, array_slice($path, $i)];
}
$entity = $next;
}
throw new CakeException(sprintf(
'Unable to fetch property `%s`.',
implode('.', $path)
));
}
/**
* Read property values or traverse arrays/iterators.
*
* @param mixed $target The entity/array/collection to fetch $field from.
* @param string $field The next field to fetch.
* @return mixed
*/
protected function _getProp(mixed $target, string $field): mixed
{
if (is_array($target) && isset($target[$field])) {
return $target[$field];
}
if ($target instanceof EntityInterface) {
return $target->get($field);
}
if ($target instanceof Traversable) {
foreach ($target as $i => $val) {
if ((string)$i === $field) {
return $val;
}
}
return false;
}
return null;
}
/**
* Check if a field should be marked as required.
*
* @param string $field The dot separated path to the field you want to check.
* @return bool|null
*/
public function isRequired(string $field): ?bool
{
$parts = explode('.', $field);
$entity = $this->entity($parts);
$isNew = true;
if ($entity instanceof EntityInterface) {
$isNew = $entity->isNew();
}
$validator = $this->_getValidator($parts);
$fieldName = array_pop($parts);
if (!$validator->hasField($fieldName)) {
return null;
}
if ($this->type($field) !== 'boolean') {
return !$validator->isEmptyAllowed($fieldName, $isNew);
}
return false;
}
/**
* @inheritDoc
*/
public function getRequiredMessage(string $field): ?string
{
$parts = explode('.', $field);
$validator = $this->_getValidator($parts);
$fieldName = array_pop($parts);
if (!$validator->hasField($fieldName)) {
return null;
}
$ruleset = $validator->field($fieldName);
if ($ruleset->isEmptyAllowed()) {
return null;
}
return $validator->getNotEmptyMessage($fieldName);
}
/**
* Get field length from validation
*
* @param string $field The dot separated path to the field you want to check.
* @return int|null
*/
public function getMaxLength(string $field): ?int
{
$parts = explode('.', $field);
$validator = $this->_getValidator($parts);
$fieldName = array_pop($parts);
if ($validator->hasField($fieldName)) {
foreach ($validator->field($fieldName)->rules() as $rule) {
if ($rule->get('rule') === 'maxLength') {
return $rule->get('pass')[0];
}
}
}
$attributes = $this->attributes($field);
if (empty($attributes['length'])) {
return null;
}
return (int)$attributes['length'];
}
/**
* Get the field names from the top level entity.
*
* If the context is for an array of entities, the 0th index will be used.
*
* @return array<string> Array of field names in the table/entity.
* @psalm-return list<string>
*/
public function fieldNames(): array
{
$table = $this->_getTable('0');
if (!$table) {
return [];
}
return $table->getSchema()->columns();
}
/**
* Get the validator associated to an entity based on naming
* conventions.
*
* @param array $parts Each one of the parts in a path for a field name
* @return \Cake\Validation\Validator
* @throws \Cake\Core\Exception\CakeException If validator cannot be retrieved based on the parts.
*/
protected function _getValidator(array $parts): Validator
{
$keyParts = array_filter(array_slice($parts, 0, -1), function ($part) {
return !is_numeric($part);
});
$key = implode('.', $keyParts);
$entity = $this->entity($parts);
if (isset($this->_validator[$key])) {
if (is_object($entity)) {
$this->_validator[$key]->setProvider('entity', $entity);
}
return $this->_validator[$key];
}
$table = $this->_getTable($parts);
if (!$table) {
throw new InvalidArgumentException(sprintf('Validator not found: `%s`.', $key));
}
$alias = $table->getAlias();
$method = 'default';
if (is_string($this->_context['validator'])) {
$method = $this->_context['validator'];
} elseif (isset($this->_context['validator'][$alias])) {
$method = $this->_context['validator'][$alias];
}
$validator = $table->getValidator($method);
if (is_object($entity)) {
$validator->setProvider('entity', $entity);
}
return $this->_validator[$key] = $validator;
}
/**
* Get the table instance from a property path
*
* @param \Cake\Datasource\EntityInterface|array<string>|string $parts Each one of the parts in a path for a field name
* @param bool $fallback Whether to fallback to the last found table
* when a nonexistent field/property is being encountered.
* @return \Cake\ORM\Table|null Table instance or null
*/
protected function _getTable(EntityInterface|array|string $parts, bool $fallback = true): ?Table
{
if (!is_array($parts) || count($parts) === 1) {
return $this->_tables[$this->_rootName];
}
$normalized = array_slice(array_filter($parts, function ($part) {
return !is_numeric($part);
}), 0, -1);
$path = implode('.', $normalized);
if (isset($this->_tables[$path])) {
return $this->_tables[$path];
}
if (current($normalized) === $this->_rootName) {
$normalized = array_slice($normalized, 1);
}
$table = $this->_tables[$this->_rootName];
$assoc = null;
foreach ($normalized as $part) {
if ($part === '_joinData') {
if ($assoc !== null) {
/** @var \Cake\ORM\Association\BelongsToMany $assoc */
$table = $assoc->junction();
$assoc = null;
continue;
}
} else {
$associationCollection = $table->associations();
$assoc = $associationCollection->getByProperty($part);
}
if ($assoc === null) {
if ($fallback) {
break;
}
return null;
}
$table = $assoc->getTarget();
}
return $this->_tables[$path] = $table;
}
/**
* Get the abstract field type for a given field name.
*
* @param string $field A dot separated path to get a schema type for.
* @return string|null An abstract data type or null.
* @see \Cake\Database\TypeFactory
*/
public function type(string $field): ?string
{
$parts = explode('.', $field);
$table = $this->_getTable($parts);
return $table?->getSchema()->baseColumnType(array_pop($parts));
}
/**
* Get an associative array of other attributes for a field name.
*
* @param string $field A dot separated path to get additional data on.
* @return array An array of data describing the additional attributes on a field.
*/
public function attributes(string $field): array
{
$parts = explode('.', $field);
$table = $this->_getTable($parts);
if (!$table) {
return [];
}
return array_intersect_key(
(array)$table->getSchema()->getColumn(array_pop($parts)),
array_flip(static::VALID_ATTRIBUTES)
);
}
/**
* Check whether a field has an error attached to it
*
* @param string $field A dot separated path to check errors on.
* @return bool Returns true if the errors for the field are not empty.
*/
public function hasError(string $field): bool
{
return $this->error($field) !== [];
}
/**
* Get the errors for a given field
*
* @param string $field A dot separated path to check errors on.
* @return array An array of errors.
*/
public function error(string $field): array
{
$parts = explode('.', $field);
try {
/**
* @var \Cake\Datasource\EntityInterface|null $entity
* @var array<string> $remainingParts
*/
[$entity, $remainingParts] = $this->leafEntity($parts);
} catch (CakeException) {
return [];
}
if ($entity instanceof EntityInterface && count($remainingParts) === 0) {
return $entity->getErrors();
}
if ($entity instanceof EntityInterface) {
$error = $entity->getError(implode('.', $remainingParts));
if ($error) {
return $error;
}
return $entity->getError(array_pop($parts));
}
return [];
}
}