EventSubscriber   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 47
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 6 1
A prePersist() 0 19 4
1
<?php
2
3
namespace LKu\DoctrineGuid;
4
5
use Doctrine\DBAL\Types\Type;
6
use Doctrine\ORM\Event\LifecycleEventArgs;
7
use Doctrine\Common\EventSubscriber as DoctrineEventSubscriber;
8
use Doctrine\ORM\Events;
9
use Doctrine\ORM\Id\AbstractIdGenerator;
10
11
final class EventSubscriber implements DoctrineEventSubscriber
12
{
13
    /** @var AbstractIdGenerator */
14
    protected $guidGenerator;
15
16
    /**
17
     * @param AbstractIdGenerator $guidGenerator
18
     */
19 1
    public function __construct(AbstractIdGenerator $guidGenerator)
20
    {
21 1
        $this->guidGenerator = $guidGenerator;
22 1
    }
23
24
    /**
25
     * @inheritdoc
26
     */
27 1
    public function getSubscribedEvents()
28
    {
29
        return [
30 1
            Events::prePersist,
31
        ];
32
    }
33
34
    /**
35
     * @param LifecycleEventArgs $args
36
     * @return void
37
     */
38 1
    public function prePersist(LifecycleEventArgs $args)
39
    {
40 1
        $entityManager = $args->getEntityManager();
41 1
        $object = $args->getObject();
42 1
        $metadata = $entityManager->getClassMetadata(get_class($object));
43
44 1
        foreach ($metadata->getFieldNames() as $field) {
45 1
            $type = $metadata->getTypeOfField($field);
46 1
            if ($type === Type::GUID) {
47 1
                $property = $metadata->getReflectionProperty($field);
48 1
                $value = $property->getValue($object);
49
50 1
                if (empty($value)) {
51 1
                    $guid = $this->guidGenerator->generate($entityManager, $object);
52 1
                    $property->setValue($object, $guid);
53
                }
54
            }
55
        }
56 1
    }
57
}
58