-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
DoctrineObject.php
803 lines (682 loc) · 24.9 KB
/
DoctrineObject.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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
<?php
declare(strict_types=1);
namespace Doctrine\Laminas\Hydrator;
use DateTime;
use DateTimeImmutable;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\InflectorFactory;
use Doctrine\Laminas\Hydrator\Strategy\AllowRemoveByReference;
use Doctrine\Laminas\Hydrator\Strategy\AllowRemoveByValue;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\ObjectManager;
use Generator;
use InvalidArgumentException;
use Laminas\Hydrator\AbstractHydrator;
use Laminas\Hydrator\Filter\FilterProviderInterface;
use Laminas\Stdlib\ArrayUtils;
use RuntimeException;
use Traversable;
use function array_filter;
use function array_flip;
use function array_intersect_key;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function assert;
use function ctype_upper;
use function current;
use function get_class;
use function get_class_methods;
use function gettype;
use function in_array;
use function is_array;
use function is_callable;
use function is_int;
use function is_object;
use function is_string;
use function method_exists;
use function property_exists;
use function sprintf;
use function strpos;
use function substr;
use const PHP_VERSION_ID;
class DoctrineObject extends AbstractHydrator
{
/** @var ObjectManager */
protected $objectManager;
/** @var ClassMetadata */
protected $metadata;
/** @var bool */
protected $byValue = true;
/** @var class-string<Strategy\AbstractCollectionStrategy> */
protected $defaultByValueStrategy = AllowRemoveByValue::class;
/** @var class-string<Strategy\AbstractCollectionStrategy> */
protected $defaultByReferenceStrategy = AllowRemoveByReference::class;
/** @var Inflector */
private $inflector;
/**
* @param ObjectManager $objectManager The ObjectManager to use
* @param bool $byValue If set to true, hydrator will always use entity's public API
*/
public function __construct(ObjectManager $objectManager, $byValue = true, ?Inflector $inflector = null)
{
$this->objectManager = $objectManager;
$this->byValue = (bool) $byValue;
$this->inflector = $inflector ?? InflectorFactory::create()->build();
}
/**
* @return class-string<Strategy\AbstractCollectionStrategy>
*/
public function getDefaultByValueStrategy()
{
return $this->defaultByValueStrategy;
}
/**
* @param class-string<Strategy\AbstractCollectionStrategy> $defaultByValueStrategy
*
* @return $this
*/
public function setDefaultByValueStrategy($defaultByValueStrategy)
{
$this->defaultByValueStrategy = $defaultByValueStrategy;
return $this;
}
/**
* @return class-string<Strategy\AbstractCollectionStrategy>
*/
public function getDefaultByReferenceStrategy()
{
return $this->defaultByReferenceStrategy;
}
/**
* @param class-string<Strategy\AbstractCollectionStrategy> $defaultByReferenceStrategy
*
* @return $this
*/
public function setDefaultByReferenceStrategy($defaultByReferenceStrategy)
{
$this->defaultByReferenceStrategy = $defaultByReferenceStrategy;
return $this;
}
/**
* Get all field names, this includes direct field names, names of embeddables and
* associations. By using a key-based generator, duplicates are effectively removed.
*
* @return Generator<string>
*/
public function getFieldNames(): iterable
{
$fields = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
foreach ($fields as $fieldName) {
$pos = strpos($fieldName, '.');
if ($pos !== false) {
$fieldName = substr($fieldName, 0, $pos);
}
yield $fieldName;
}
}
/**
* Extract values from an object
*/
public function extract(object $object): array
{
$this->prepare($object);
if ($this->byValue) {
return $this->extractByValue($object);
}
return $this->extractByReference($object);
}
/**
* Hydrate $object with the provided $data.
*
* {@inheritDoc}
*/
public function hydrate(array $data, object $object)
{
$this->prepare($object);
if ($this->byValue) {
return $this->hydrateByValue($data, $object);
}
return $this->hydrateByReference($data, $object);
}
/**
* Prepare the hydrator by adding strategies to every collection valued associations
*
* @param object $object
*/
protected function prepare($object)
{
$this->metadata = $this->objectManager->getClassMetadata(get_class($object));
$this->prepareStrategies();
}
/**
* Prepare strategies before the hydrator is used
*
* @throws InvalidArgumentException
*/
protected function prepareStrategies()
{
$associations = $this->metadata->getAssociationNames();
foreach ($associations as $association) {
if (! $this->metadata->isCollectionValuedAssociation($association)) {
continue;
}
// Add a strategy if the association has none set by user
if (! $this->hasStrategy($association)) {
if ($this->byValue) {
$strategyClassName = $this->getDefaultByValueStrategy();
} else {
$strategyClassName = $this->getDefaultByReferenceStrategy();
}
$this->addStrategy($association, new $strategyClassName());
}
$strategy = $this->getStrategy($association);
if (! $strategy instanceof Strategy\AbstractCollectionStrategy) {
throw new InvalidArgumentException(
sprintf(
'Strategies used for collections valued associations must inherit from '
. 'Strategy\AbstractCollectionStrategy, %s given',
get_class($strategy)
)
);
}
$strategy->setCollectionName($association)
->setClassMetadata($this->metadata);
}
}
/**
* Extract values from an object using a by-value logic (this means that it uses the entity
* API, in this case, getters)
*
* @param object $object
*
* @return array
*
* @throws RuntimeException
*/
protected function extractByValue($object)
{
$methods = get_class_methods($object);
$filter = $object instanceof FilterProviderInterface
? $object->getFilter()
: $this->filterComposite;
$data = [];
foreach ($this->getFieldNames() as $fieldName) {
if ($filter && ! $filter->filter($fieldName)) {
continue;
}
$getter = 'get' . $this->inflector->classify($fieldName);
$isser = 'is' . $this->inflector->classify($fieldName);
$dataFieldName = $this->computeExtractFieldName($fieldName);
if (in_array($getter, $methods)) {
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$getter(), $object);
} elseif (in_array($isser, $methods)) {
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$isser(), $object);
} elseif (
substr($fieldName, 0, 2) === 'is'
&& ctype_upper(substr($fieldName, 2, 1))
&& in_array($fieldName, $methods)
) {
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$fieldName(), $object);
}
// Unknown fields are ignored
}
return $data;
}
/**
* Extract values from an object using a by-reference logic (this means that values are
* directly fetched without using the public API of the entity, in this case, getters)
*
* @param object $object
*
* @return array
*/
protected function extractByReference($object)
{
$refl = $this->metadata->getReflectionClass();
$filter = $object instanceof FilterProviderInterface
? $object->getFilter()
: $this->filterComposite;
$data = [];
foreach ($this->getFieldNames() as $fieldName) {
if ($filter && ! $filter->filter($fieldName)) {
continue;
}
$reflProperty = $refl->getProperty($fieldName);
$reflProperty->setAccessible(true);
// skip uninitialized properties (available from PHP 7.4)
if (PHP_VERSION_ID >= 70400 && ! $reflProperty->isInitialized($object)) {
continue;
}
$dataFieldName = $this->computeExtractFieldName($fieldName);
$data[$dataFieldName] = $this->extractValue($fieldName, $reflProperty->getValue($object), $object);
}
return $data;
}
/**
* Converts a value for hydration
* Apply strategies first, then the type conversions
*
* @param string $name The name of the strategy to use.
* @param mixed $value The value that should be converted.
* @param array|null $data The whole data is optionally provided as context.
*
* @return mixed|null
*/
public function hydrateValue(string $name, $value, ?array $data = null)
{
$value = parent::hydrateValue($name, $value, $data);
if ($value === null && $this->isNullable($name)) {
return null;
}
return $this->handleTypeConversions($value, $this->metadata->getTypeOfField($name));
}
/**
* Hydrate the object using a by-value logic (this means that it uses the entity API, in this
* case, setters)
*
* @param object $object
* @psalm-param T $object
*
* @return object
* @psalm-return T
*
* @throws RuntimeException
*
* @template T of object
*/
protected function hydrateByValue(array $data, $object)
{
$tryObject = $this->tryConvertArrayToObject($data, $object);
$metadata = $this->metadata;
if (is_object($tryObject)) {
$object = $tryObject;
}
foreach ($data as $field => $value) {
$field = $this->computeHydrateFieldName($field);
$setter = 'set' . $this->inflector->classify($field);
if ($metadata->hasAssociation($field)) {
$target = $metadata->getAssociationTargetClass($field);
assert($target !== null);
if ($metadata->isSingleValuedAssociation($field)) {
if (! is_callable([$object, $setter])) {
continue;
}
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
if (
$value === null
&& ! current($metadata->getReflectionClass()->getMethod($setter)->getParameters())->allowsNull()
) {
continue;
}
$object->$setter($value);
} elseif ($metadata->isCollectionValuedAssociation($field)) {
$this->toMany($object, $field, $target, $value);
}
} else {
if (! is_callable([$object, $setter])) {
continue;
}
$object->$setter($this->hydrateValue($field, $value, $data));
}
$this->metadata = $metadata;
}
return $object;
}
/**
* Hydrate the object using a by-reference logic (this means that values are modified directly without
* using the public API, in this case setters, and hence override any logic that could be done in those
* setters)
*
* @param object $object
* @psalm-param T $object
*
* @return object
* @psalm-return T
*
* @template T of object
*/
protected function hydrateByReference(array $data, $object)
{
$tryObject = $this->tryConvertArrayToObject($data, $object);
$metadata = $this->metadata;
$refl = $metadata->getReflectionClass();
if (is_object($tryObject)) {
$object = $tryObject;
}
foreach ($data as $field => $value) {
$field = $this->computeHydrateFieldName($field);
// Ignore unknown fields
if (! $refl->hasProperty($field)) {
continue;
}
$reflProperty = $refl->getProperty($field);
$reflProperty->setAccessible(true);
if ($metadata->hasAssociation($field)) {
$target = $metadata->getAssociationTargetClass($field);
assert($target !== null);
if ($metadata->isSingleValuedAssociation($field)) {
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
$reflProperty->setValue($object, $value);
} elseif ($metadata->isCollectionValuedAssociation($field)) {
$this->toMany($object, $field, $target, $value);
}
} else {
$reflProperty->setValue($object, $this->hydrateValue($field, $value, $data));
}
$this->metadata = $metadata;
}
return $object;
}
/**
* This function tries, given an array of data, to convert it to an object if the given array contains
* an identifier for the object. This is useful in a context of updating existing entities, without ugly
* tricks like setting manually the existing id directly into the entity
*
* @param array $data The data that may contain identifiers keys
* @param object $object
* @psalm-param T $object
*
* @return object|null
* @psalm-return T|null
*
* @template T of object
*/
protected function tryConvertArrayToObject($data, $object)
{
$metadata = $this->metadata;
$identifierNames = $metadata->getIdentifierFieldNames();
$identifierValues = [];
if (empty($identifierNames)) {
return $object;
}
foreach ($identifierNames as $identifierName) {
if (! isset($data[$identifierName])) {
return $object;
}
$identifierValues[$identifierName] = $data[$identifierName];
}
/** @var class-string<T> $targetClass */
$targetClass = $metadata->getName();
return $this->find($identifierValues, $targetClass);
}
/**
* Handle ToOne associations
* When $value is an array but is not the $target's identifiers, $value is
* most likely an array of fieldset data. The identifiers will be determined
* and a target instance will be initialized and then hydrated. The hydrated
* target will be returned.
*
* @param class-string $target
* @param mixed $value
*
* @return object|null
*/
protected function toOne($target, $value)
{
$metadata = $this->objectManager->getClassMetadata($target);
if (is_array($value) && array_keys($value) !== $metadata->getIdentifier()) {
// $value is most likely an array of fieldset data
$identifiers = array_intersect_key(
$value,
array_flip($metadata->getIdentifier())
);
$object = $this->find($identifiers, $target) ?: new $target();
return $this->hydrate($value, $object);
}
return $this->find($value, $target);
}
/**
* Handle ToMany associations. In proper Doctrine design, Collections should not be swapped, so
* collections are always handled by reference. Internally, every collection is handled using specials
* strategies that inherit from AbstractCollectionStrategy class, and that add or remove elements but without
* changing the collection of the object
*
* @param object $object
* @param mixed $collectionName
* @param class-string $target
* @param mixed $values
*
* @throws InvalidArgumentException
*/
protected function toMany($object, $collectionName, $target, $values)
{
$metadata = $this->objectManager->getClassMetadata($target);
$identifier = $metadata->getIdentifier();
if (! is_array($values) && ! $values instanceof Traversable) {
$values = (array) $values;
} elseif ($values instanceof Traversable) {
$values = ArrayUtils::iteratorToArray($values);
}
$collection = [];
// If the collection contains identifiers, fetch the objects from database
foreach ($values as $value) {
if ($value instanceof $target) {
// assumes modifications have already taken place in object
$collection[] = $value;
continue;
}
if (empty($value)) {
// assumes no id and retrieves new $target
$collection[] = $this->find($value, $target);
continue;
}
$find = [];
if (is_array($identifier)) {
foreach ($identifier as $field) {
switch (gettype($value)) {
case 'object':
$getter = 'get' . $this->inflector->classify($field);
if (is_callable([$value, $getter])) {
$find[$field] = $value->$getter();
} elseif (property_exists($value, $field)) {
$find[$field] = $value->$field;
}
break;
case 'array':
if (array_key_exists($field, $value) && $value[$field] !== null) {
$find[$field] = $value[$field];
unset($value[$field]); // removed identifier from persistable data
}
break;
default:
$find[$field] = $value;
break;
}
}
}
if (! empty($find)) {
$found = $this->find($find, $target);
if ($found) {
$collection[] = is_array($value) ? $this->hydrate($value, $found) : $found;
continue;
}
}
$collection[] = is_array($value) ? $this->hydrate($value, new $target()) : new $target();
}
$collection = array_filter(
$collection,
static function ($item) {
return $item !== null;
}
);
// Set the object so that the strategy can extract the Collection from it
$collectionStrategy = $this->getStrategy($collectionName);
assert($collectionStrategy instanceof Strategy\AbstractCollectionStrategy);
$collectionStrategy->setObject($object);
// We could directly call hydrate method from the strategy, but if people want to override
// hydrateValue function, they can do it and do their own stuff
$this->hydrateValue($collectionName, $collection, $values);
}
/**
* Handle various type conversions that should be supported natively by Doctrine (like DateTime)
* See Documentation of Doctrine Mapping Types for defaults
*
* @link http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#doctrine-mapping-types
*
* @param mixed $value
* @param ?string $typeOfField
*
* @return mixed|null
*/
protected function handleTypeConversions($value, $typeOfField)
{
if ($value === null) {
return null;
}
switch ($typeOfField) {
case 'boolean':
$value = (bool) $value;
break;
case 'string':
case 'text':
case 'bigint':
case 'decimal':
$value = (string) $value;
break;
case 'integer':
case 'smallint':
$value = (int) $value;
break;
case 'float':
$value = (float) $value;
break;
case 'datetimetz':
case 'datetimetz_immutable':
case 'datetime':
case 'datetime_immutable':
case 'time':
case 'date':
if ($value === '') {
return null;
}
$isImmutable = substr($typeOfField, -9) === 'immutable';
// Psalm has troubles with nested conditions, therefore break this into two return statements.
// See https://github.com/vimeo/psalm/issues/6683.
if ($isImmutable && $value instanceof DateTimeImmutable) {
return $value;
}
if (! $isImmutable && $value instanceof DateTime) {
return $value;
}
if ($isImmutable && $value instanceof DateTime) {
return DateTimeImmutable::createFromMutable($value);
}
if (! $isImmutable && $value instanceof DateTimeImmutable) {
return DateTime::createFromImmutable($value);
}
if (is_int($value)) {
$dateTime = $isImmutable
? new DateTimeImmutable()
: new DateTime();
return $dateTime->setTimestamp($value);
}
if (is_string($value)) {
return $isImmutable
? new DateTimeImmutable($value)
: new DateTime($value);
}
break;
default:
break;
}
return $value;
}
/**
* Find an object by a given target class and identifier
*
* @param mixed $identifiers
* @param string $targetClass
* @psalm-param class-string<T> $targetClass
*
* @return object|null
* @psalm-return T|null
*
* @template T of object
*/
protected function find($identifiers, $targetClass)
{
if ($identifiers instanceof $targetClass) {
return $identifiers;
}
if ($this->isNullIdentifier($identifiers)) {
return null;
}
return $this->objectManager->find($targetClass, $identifiers);
}
/**
* Verifies if a provided identifier is to be considered null
*
* @param mixed $identifier
*
* @return bool
*/
private function isNullIdentifier($identifier)
{
if ($identifier === null) {
return true;
}
if ($identifier instanceof Traversable || is_array($identifier)) {
// Psalm infers iterable as a union of array|Traversable, but
// ArrayUtils::iteratorToArray() doesn't accept iterable, so this
// needs to be overwritten manually here.
// See https://github.com/vimeo/psalm/issues/6682
/** @psalm-var array|Traversable $identifier */
$nonNullIdentifiers = array_filter(
ArrayUtils::iteratorToArray($identifier),
static function ($value) {
return $value !== null;
}
);
return empty($nonNullIdentifiers);
}
return false;
}
/**
* Check the field is nullable
*
* @param string $name
*
* @return bool
*/
private function isNullable($name)
{
//TODO: need update after updating isNullable method of Doctrine\ORM\Mapping\ClassMetadata
if ($this->metadata->hasField($name)) {
return method_exists($this->metadata, 'isNullable') && $this->metadata->isNullable($name);
}
if ($this->metadata->hasAssociation($name) && method_exists($this->metadata, 'getAssociationMapping')) {
$mapping = $this->metadata->getAssociationMapping($name);
return $mapping !== false && isset($mapping['nullable']) && $mapping['nullable'];
}
return false;
}
/**
* Applies the naming strategy if there is one set
*
* @param string $field
*
* @return string
*/
protected function computeHydrateFieldName($field)
{
if ($this->hasNamingStrategy()) {
$field = $this->getNamingStrategy()->hydrate($field);
}
return $field;
}
/**
* Applies the naming strategy if there is one set
*
* @param string $field
*
* @return string
*/
protected function computeExtractFieldName($field)
{
if ($this->hasNamingStrategy()) {
$field = $this->getNamingStrategy()->extract($field);
}
return $field;
}
}