1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Validation; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
6
|
|
|
use Doctrine\ORM\PersistentCollection; |
7
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\EntityInterface; |
8
|
|
|
|
9
|
|
|
class Initialiser |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var EntityManagerInterface |
13
|
|
|
*/ |
14
|
|
|
private $entityManager; |
15
|
|
|
|
16
|
|
|
private $visited = []; |
17
|
|
|
|
18
|
|
|
public function __construct(EntityManagerInterface $entityManager) |
19
|
|
|
{ |
20
|
|
|
$this->entityManager = $entityManager; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function initialise(object $entityOrDto): void |
24
|
|
|
{ |
25
|
|
|
$this->visited = []; |
26
|
|
|
$this->initialiseObject($entityOrDto); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
private function initialiseObject(object $object): void |
30
|
|
|
{ |
31
|
|
|
if (true === $this->isVisited($object)) { |
32
|
|
|
return; |
33
|
|
|
} |
34
|
|
|
$this->setAsVisited($object); |
35
|
|
|
$this->entityManager->initializeObject($object); |
36
|
|
|
if ($object instanceof EntityInterface) { |
37
|
|
|
$this->initialiseProperties($object); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function isVisited(object $object): bool |
42
|
|
|
{ |
43
|
|
|
return isset($this->visited[spl_object_hash($object)]); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function setAsVisited(object $object): void |
47
|
|
|
{ |
48
|
|
|
$this->visited[spl_object_hash($object)] = true; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function initialiseProperties(EntityInterface $entity): void |
52
|
|
|
{ |
53
|
|
|
$getters = $entity::getDoctrineStaticMeta()->getGetters(); |
54
|
|
|
foreach ($getters as $getter) { |
55
|
|
|
try { |
56
|
|
|
$got = $entity->$getter(); |
57
|
|
|
} catch (\TypeError $e) { |
58
|
|
|
//getters for things that have not yet been set will return null |
59
|
|
|
//but they might be required. This should be caught by the validation, not cause a type error here |
60
|
|
|
continue; |
61
|
|
|
} |
62
|
|
|
if (false === is_object($got)) { |
63
|
|
|
continue; |
64
|
|
|
} |
65
|
|
|
if ($got instanceof EntityInterface) { |
66
|
|
|
$this->initialiseObject($got); |
67
|
|
|
continue; |
68
|
|
|
} |
69
|
|
|
if ($got instanceof PersistentCollection) { |
70
|
|
|
$this->initialiseObject($got); |
71
|
|
|
continue; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|