1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cypress\PatchManager\Handler; |
4
|
|
|
|
5
|
|
|
use Cypress\PatchManager\OperationData; |
6
|
|
|
use Cypress\PatchManager\Patchable; |
7
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
8
|
|
|
use Doctrine\Persistence\Proxy; |
9
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccess; |
10
|
|
|
|
11
|
|
|
class DataDoctrineHandler extends DataHandler |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var EntityManagerInterface |
15
|
|
|
*/ |
16
|
|
|
private EntityManagerInterface $entityManagerInterface; |
|
|
|
|
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param EntityManagerInterface $entityManagerInterface |
20
|
|
|
*/ |
21
|
6 |
|
public function __construct(EntityManagerInterface $entityManagerInterface) |
22
|
|
|
{ |
23
|
6 |
|
$this->entityManagerInterface = $entityManagerInterface; |
24
|
6 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param Patchable $subject |
28
|
|
|
* @param OperationData $operationData |
29
|
|
|
* @throws \Doctrine\Persistence\Mapping\MappingException |
30
|
|
|
* @throws \ReflectionException |
31
|
|
|
*/ |
32
|
4 |
|
public function handle(Patchable $subject, OperationData $operationData): void |
33
|
|
|
{ |
34
|
4 |
|
$propertyAccessorBuilder = PropertyAccess::createPropertyAccessorBuilder(); |
35
|
4 |
|
$propertyAccessorBuilder = $this->magicCall ? $propertyAccessorBuilder->enableMagicCall() : $propertyAccessorBuilder; |
36
|
|
|
|
37
|
4 |
|
$propertyAccessor = $propertyAccessorBuilder->getPropertyAccessor(); |
38
|
4 |
|
$property = $operationData->get('property')->get(); |
39
|
4 |
|
$value = $operationData->get('value')->get(); |
40
|
4 |
|
if ($this->isEntity($subject)) { |
41
|
|
|
// if it's an associated entity I fetch if from the db |
42
|
3 |
|
$metadata = $this->entityManagerInterface->getMetadataFactory()->getMetadataFor(get_class($subject)); |
43
|
3 |
|
if (in_array($property, $metadata->getAssociationNames())) { |
44
|
2 |
|
$targetClass = $metadata->getAssociationTargetClass($property); |
45
|
2 |
|
$value = $this->entityManagerInterface->find($targetClass, $value); |
46
|
|
|
} |
47
|
|
|
// if it's a date field I cast the value to date |
48
|
3 |
|
$fieldType = $metadata->getTypeOfField($property); |
49
|
3 |
|
if ('date' === $fieldType) { |
50
|
1 |
|
$value = new \DateTime($value); |
51
|
|
|
} |
52
|
|
|
} |
53
|
4 |
|
$propertyAccessor->setValue($subject, $property, $value); |
54
|
4 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param object|string $class |
58
|
|
|
* |
59
|
|
|
* @return bool |
60
|
|
|
*/ |
61
|
5 |
|
private function isEntity($class): bool |
62
|
|
|
{ |
63
|
5 |
|
if (is_object($class)) { |
64
|
4 |
|
$class = $class instanceof Proxy ? get_parent_class($class) : get_class($class); |
65
|
|
|
|
66
|
4 |
|
return !$this->entityManagerInterface->getMetadataFactory()->isTransient($class); |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
return false; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|