1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of Goodwix Doctrine JSON ODM. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Goodwix\DoctrineJsonOdm\Service; |
10
|
|
|
|
11
|
|
|
use Doctrine\Common\Annotations\Reader; |
12
|
|
|
use Goodwix\DoctrineJsonOdm\Annotation\ODM; |
13
|
|
|
use Goodwix\DoctrineJsonOdm\Type\ODMType; |
14
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
15
|
|
|
|
16
|
|
|
class ODMAutoRegistrar |
17
|
|
|
{ |
18
|
|
|
/** @var SerializerInterface */ |
19
|
|
|
private $serializer; |
20
|
|
|
|
21
|
|
|
/** @var Reader */ |
22
|
|
|
private $annotationReader; |
23
|
|
|
|
24
|
|
|
/** @var string[] */ |
25
|
|
|
private $entityClassList; |
26
|
|
|
|
27
|
14 |
|
public function __construct(SerializerInterface $serializer, Reader $annotationReader, array $entityClassList) |
28
|
|
|
{ |
29
|
14 |
|
$this->serializer = $serializer; |
30
|
14 |
|
$this->annotationReader = $annotationReader; |
31
|
14 |
|
$this->entityClassList = $entityClassList; |
32
|
14 |
|
} |
33
|
|
|
|
34
|
14 |
|
public function registerODMTypes(): void |
35
|
|
|
{ |
36
|
14 |
|
foreach ($this->entityClassList as $entityClass) { |
37
|
14 |
|
$this->assertClassExists($entityClass); |
38
|
|
|
|
39
|
13 |
|
if (!ODMType::hasType($entityClass)) { |
40
|
3 |
|
$annotation = $this->readODMAnnotation($entityClass); |
41
|
12 |
|
$this->registerODMType($entityClass, $annotation); |
42
|
|
|
} |
43
|
|
|
} |
44
|
12 |
|
} |
45
|
|
|
|
46
|
14 |
|
private function assertClassExists(string $entityClass): void |
47
|
|
|
{ |
48
|
14 |
|
if (!class_exists($entityClass) && !interface_exists($entityClass)) { |
49
|
1 |
|
throw new \DomainException( |
50
|
1 |
|
sprintf('Invalid ODM entity class: "%s".', $entityClass) |
51
|
|
|
); |
52
|
|
|
} |
53
|
13 |
|
} |
54
|
|
|
|
55
|
3 |
|
private function readODMAnnotation(string $entityClass): ODM |
56
|
|
|
{ |
57
|
3 |
|
$reflectionClass = new \ReflectionClass($entityClass); |
58
|
3 |
|
$annotation = $this->annotationReader->getClassAnnotation($reflectionClass, ODM::class); |
59
|
|
|
|
60
|
3 |
|
if (!$annotation instanceof ODM) { |
61
|
1 |
|
throw new \DomainException( |
62
|
1 |
|
sprintf('ODM class "%s" has no valid annotation.', $entityClass) |
63
|
|
|
); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
return $annotation; |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
private function registerODMType(string $entityClass, ODM $annotation): void |
70
|
|
|
{ |
71
|
2 |
|
ODMType::registerODMType($entityClass, $this->serializer); |
72
|
|
|
|
73
|
|
|
/** @var ODMType $type */ |
74
|
2 |
|
$type = ODMType::getType($entityClass); |
75
|
2 |
|
$type->setSerializationContext($annotation->serializationContext); |
76
|
2 |
|
$type->setDeserializationContext($annotation->deserializationContext); |
77
|
2 |
|
} |
78
|
|
|
} |
79
|
|
|
|