-
Notifications
You must be signed in to change notification settings - Fork 284
/
UuidableEventSubscriber.php
55 lines (45 loc) · 1.49 KB
/
UuidableEventSubscriber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace Knp\DoctrineBehaviors\EventSubscriber;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Events;
use Knp\DoctrineBehaviors\Contract\Entity\UuidableInterface;
final class UuidableEventSubscriber implements EventSubscriberInterface
{
public function loadClassMetadata(LoadClassMetadataEventArgs $loadClassMetadataEventArgs): void
{
$classMetadata = $loadClassMetadataEventArgs->getClassMetadata();
if ($classMetadata->reflClass === null) {
// Class has not yet been fully built, ignore this event
return;
}
if (! is_a($classMetadata->reflClass->getName(), UuidableInterface::class, true)) {
return;
}
if ($classMetadata->hasField('uuid')) {
return;
}
$classMetadata->mapField([
'fieldName' => 'uuid',
'type' => 'string',
'nullable' => true,
]);
}
public function prePersist(LifecycleEventArgs $lifecycleEventArgs): void
{
$entity = $lifecycleEventArgs->getEntity();
if (! $entity instanceof UuidableInterface) {
return;
}
$entity->generateUuid();
}
/**
* @return string[]
*/
public function getSubscribedEvents(): array
{
return [Events::loadClassMetadata, Events::prePersist];
}
}