Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
84.38% |
27 / 32 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
DoctrineUtils | |
84.38% |
27 / 32 |
|
50.00% |
2 / 4 |
21.53 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
hasOneToManyWithProperty | |
50.00% |
2 / 4 |
|
0.00% |
0 / 1 |
4.12 | |||
loadAll | |
88.00% |
22 / 25 |
|
0.00% |
0 / 1 |
15.39 | |||
loadAllProxies | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | namespace Apie\DoctrineEntityDatalayer; |
3 | |
4 | use Apie\StorageMetadata\Attributes\GetSearchIndexAttribute; |
5 | use Apie\StorageMetadata\Attributes\OneToManyAttribute; |
6 | use Doctrine\ORM\PersistentCollection; |
7 | use Doctrine\Persistence\Proxy; |
8 | use ReflectionClass; |
9 | use ReflectionProperty; |
10 | |
11 | final class DoctrineUtils |
12 | { |
13 | /** |
14 | * @var array<string|int, object> |
15 | */ |
16 | private array $visited = []; |
17 | private function __construct() |
18 | { |
19 | } |
20 | |
21 | private function hasOneToManyWithProperty(ReflectionProperty $property): bool |
22 | { |
23 | foreach ($property->getAttributes(OneToManyAttribute::class) as $oneToManyAttribute) { |
24 | if ($oneToManyAttribute->newInstance()->propertyName === null) { |
25 | return false; |
26 | } |
27 | } |
28 | return true; |
29 | } |
30 | |
31 | private function loadAll(object $entity): void |
32 | { |
33 | $hash = spl_object_hash($entity); |
34 | if (isset($this->visited[$hash])) { |
35 | return; |
36 | } |
37 | $this->visited[$hash] = $entity; |
38 | if ($entity instanceof Proxy) { |
39 | $entity->__load(); |
40 | } |
41 | if ($entity instanceof PersistentCollection) { |
42 | $entity->initialize(); |
43 | foreach ($entity as $item) { |
44 | $this->loadAll($item); |
45 | } |
46 | } |
47 | foreach ((new ReflectionClass($entity))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { |
48 | if ($property->isStatic() || !$property->isInitialized($entity)) { |
49 | continue; |
50 | } |
51 | if (str_starts_with($property->name, '_index')) { |
52 | continue; |
53 | } |
54 | $attributes = $property->getAttributes(GetSearchIndexAttribute::class); |
55 | if (!empty($attributes) || !$this->hasOneToManyWithProperty($property)) { |
56 | continue; |
57 | } |
58 | |
59 | $propertyValue = $property->getValue($entity); |
60 | if (is_object($propertyValue)) { |
61 | $this->loadAll($propertyValue); |
62 | } |
63 | if (is_array($propertyValue)) { |
64 | foreach ($propertyValue as $arrayItem) { |
65 | if (is_object($arrayItem)) { |
66 | $this->loadAll($arrayItem); |
67 | } |
68 | } |
69 | } |
70 | } |
71 | } |
72 | |
73 | public static function loadAllProxies(object $entity): void |
74 | { |
75 | $worker = new self(); |
76 | $worker->loadAll($entity); |
77 | } |
78 | } |