UpdatedEntityListener::preUpdate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Dontdrinkandroot\Event\Listener;
4
5
use DateTime;
6
use Doctrine\ORM\Event\LifecycleEventArgs;
7
use Dontdrinkandroot\Entity\UpdatedEntityInterface;
8
use Dontdrinkandroot\Entity\UpdatedTimestampEntityInterface;
9
10
/**
11
 * @author Philip Washington Sorst <[email protected]>
12
 */
13
class UpdatedEntityListener
14
{
15 32
    public function prePersist(LifecycleEventArgs $args): void
16
    {
17 32
        $this->checkAndSetUpdated($args);
18 32
    }
19
20 4
    public function preUpdate(LifecycleEventArgs $args): void
21
    {
22 4
        $this->checkAndSetUpdated($args);
23 4
    }
24
25 32
    protected function checkAndSetUpdated(LifecycleEventArgs $args): void
26
    {
27 32
        $entity = $args->getEntity();
28
29 32
        if (is_a($entity, UpdatedEntityInterface::class)) {
30
            /** @var UpdatedEntityInterface $updatedEntity */
31 32
            $updatedEntity = $entity;
32 32
            $updatedEntity->setUpdated(new DateTime());
33
        }
34
35 32
        if (is_a($entity, UpdatedTimestampEntityInterface::class)) {
36
            /** @var UpdatedTimestampEntityInterface $updatedTimestampEntity */
37
            $updatedTimestampEntity = $entity;
38
            if (null === $updatedTimestampEntity->getUpdatedTimestamp()) {
39
                $updatedTimestampEntity->setUpdatedTimestamp((int)(microtime(true) * 1000));
40
            }
41
        }
42 32
    }
43
}
44