LifecycleDateListener   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 8
eloc 18
dl 0
loc 51
rs 10
c 3
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A prePersist() 0 7 2
A preUpdate() 0 6 2
A getSubscribedEvents() 0 6 1
A loadClassMetadata() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Christian Gripp <[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
namespace Core23\Doctrine\EventListener\ORM;
13
14
use Core23\Doctrine\Model\LifecycleDateTimeInterface;
15
use Core23\Doctrine\Model\Traits\LifecycleDateTimeTrait;
16
use Core23\Doctrine\Util\ClassUtils;
17
use DateTime;
18
use Doctrine\ORM\Event\LifecycleEventArgs;
19
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
20
use Doctrine\ORM\Events;
21
use Doctrine\ORM\Mapping\MappingException;
22
23
final class LifecycleDateListener extends AbstractListener
24
{
25
    public function getSubscribedEvents()
26
    {
27
        return [
28
            Events::prePersist,
29
            Events::preUpdate,
30
            Events::loadClassMetadata,
31
        ];
32
    }
33
34
    /**
35
     * Start lifecycle.
36
     */
37
    public function prePersist(LifecycleEventArgs $args): void
38
    {
39
        $object = $args->getObject();
40
41
        if ($object instanceof LifecycleDateTimeInterface) {
42
            $object->setCreatedAt(new DateTime());
43
            $object->setUpdatedAt(new DateTime());
44
        }
45
    }
46
47
    /**
48
     * Update LifecycleDateTime.
49
     */
50
    public function preUpdate(LifecycleEventArgs $args): void
51
    {
52
        $object = $args->getObject();
53
54
        if ($object instanceof LifecycleDateTimeInterface) {
55
            $object->setUpdatedAt(new DateTime());
56
        }
57
    }
58
59
    /**
60
     * @throws MappingException
61
     */
62
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
63
    {
64
        $meta = $eventArgs->getClassMetadata();
65
66
        $reflClass = $meta->getReflectionClass();
67
68
        if (null === $reflClass || !ClassUtils::containsTrait($reflClass, LifecycleDateTimeTrait::class)) {
69
            return;
70
        }
71
72
        $this->createDateTimeField($meta, 'createdAt', false);
73
        $this->createDateTimeField($meta, 'updatedAt', false);
74
    }
75
}
76