DoctrineEventSubscriber::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
/*
3
 * This file is part of the FreshTimestampableEntityBundle
4
 *
5
 * (c) Artem Henvald <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Fresh\TimestampableEntityBundle\EventListener;
14
15
use Doctrine\ORM\Event\LifecycleEventArgs;
16
use Doctrine\ORM\Events;
17
use Fresh\TimestampableEntityBundle\Model\TimestampableInterface;
18
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
19
20
/**
21
 * DoctrineEventSubscriber.
22
 *
23
 * @author Artem Henvald <[email protected]>
24
 */
25
class DoctrineEventSubscriber implements EventSubscriberInterface
26
{
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public static function getSubscribedEvents(): array
31
    {
32
        return [
33
            Events::prePersist => 'prePersist',
34
            Events::preUpdate => 'preUpdate',
35
        ];
36
    }
37
38
    /**
39
     * @param LifecycleEventArgs $args
40
     */
41
    public function prePersist(LifecycleEventArgs $args): void
42
    {
43
        if ($args->getEntity() instanceof TimestampableInterface) {
44
            $args->getEntity()->setCreatedAt(new \DateTimeImmutable('now'))
45
                              ->setUpdatedAt(new \DateTime('now'));
46
        }
47
    }
48
49
    /**
50
     * @param LifecycleEventArgs $args
51
     */
52
    public function preUpdate(LifecycleEventArgs $args): void
53
    {
54
        if ($args->getEntity() instanceof TimestampableInterface) {
55
            $args->getEntity()->setUpdatedAt(new \DateTime('now'));
56
        }
57
    }
58
}
59