1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Component Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Silverback\ApiComponentBundle\Doctrine\EventSubscriber; |
15
|
|
|
|
16
|
|
|
use Doctrine\Common\Annotations\Reader; |
17
|
|
|
use Doctrine\Common\EventSubscriber; |
18
|
|
|
use Doctrine\ORM\Events; |
19
|
|
|
use Doctrine\ORM\Mapping\ClassMetadataInfo; |
20
|
|
|
use Doctrine\ORM\Mapping\NamingStrategy; |
21
|
|
|
use Doctrine\Persistence\Event\LoadClassMetadataEventArgs; |
22
|
|
|
use Silverback\ApiComponentBundle\Annotation\Publishable; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @author Vincent Chalamon <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
final class PublishableEventSubscriber implements EventSubscriber |
28
|
|
|
{ |
29
|
|
|
private Reader $reader; |
30
|
|
|
|
31
|
9 |
|
public function __construct(Reader $reader) |
32
|
|
|
{ |
33
|
9 |
|
$this->reader = $reader; |
34
|
9 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* {@inheritdoc} |
38
|
|
|
*/ |
39
|
9 |
|
public function getSubscribedEvents(): array |
40
|
|
|
{ |
41
|
|
|
return [ |
42
|
9 |
|
Events::loadClassMetadata, |
43
|
|
|
]; |
44
|
|
|
} |
45
|
|
|
|
46
|
9 |
|
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void |
47
|
|
|
{ |
48
|
|
|
/** @var ClassMetadataInfo $metadata */ |
49
|
9 |
|
$metadata = $eventArgs->getClassMetadata(); |
50
|
|
|
/** @var Publishable $annotation */ |
51
|
9 |
|
if (!$annotation = $this->reader->getClassAnnotation($metadata->getReflectionClass(), Publishable::class)) { |
52
|
9 |
|
return; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** @var NamingStrategy $namingStrategy */ |
56
|
|
|
$namingStrategy = $eventArgs |
57
|
|
|
->getEntityManager() |
|
|
|
|
58
|
|
|
->getConfiguration() |
59
|
|
|
->getNamingStrategy(); |
60
|
|
|
|
61
|
|
|
if (!$metadata->hasField($annotation->fieldName)) { |
62
|
|
|
$metadata->mapField([ |
63
|
|
|
'fieldName' => $annotation->fieldName, |
64
|
|
|
'type' => 'date', |
65
|
|
|
'nullable' => true, |
66
|
|
|
]); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
if (!$metadata->hasAssociation($annotation->associationName)) { |
70
|
|
|
$metadata->mapOneToOne([ |
71
|
|
|
'fieldName' => $annotation->associationName, |
72
|
|
|
'targetEntity' => $metadata->getName(), |
73
|
|
|
'joinColumns' => [ |
74
|
|
|
[ |
75
|
|
|
'name' => $namingStrategy->joinKeyColumnName($metadata->getName()), |
76
|
|
|
'referencedColumnName' => $namingStrategy->referenceColumnName(), |
77
|
|
|
'onDelete' => 'SET NULL', |
78
|
|
|
], |
79
|
|
|
], |
80
|
|
|
]); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|