TimestampSubscriber   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 6
Bugs 2 Features 1
Metric Value
c 6
b 2
f 1
dl 0
loc 66
wmc 7
lcom 0
cbo 3
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 7 1
A handleMetadataLoad() 0 22 2
A handlePersist() 0 20 4
1
<?php
2
3
/*
4
 * This file is part of Sulu.
5
 *
6
 * (c) MASSIVE ART WebServices GmbH
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Sulu\Component\DocumentManager\Subscriber\Behavior\Audit;
13
14
use Sulu\Component\DocumentManager\Behavior\Audit\TimestampBehavior;
15
use Sulu\Component\DocumentManager\Event\PersistEvent;
16
use Sulu\Component\DocumentManager\Events;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
19
/**
20
 * Manage the timestamp (created, changed) fields on
21
 * documents before they are persisted.
22
 */
23
class TimestampSubscriber implements EventSubscriberInterface
24
{
25
    const CREATED = 'created';
26
    const CHANGED = 'changed';
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public static function getSubscribedEvents()
32
    {
33
        return [
34
            Events::PERSIST => 'handlePersist',
35
            Events::METADATA_LOAD => 'handleMetadataLoad',
36
        ];
37
    }
38
39
    /**
40
     * @param MetadataLoadEvent
41
     */
42
    public function handleMetadataLoad($event)
43
    {
44
        if (!$event->getMetadata()->getReflectionClass()->isSubclassOf(TimestampBehavior::class)) {
45
            return;
46
        }
47
48
        $metadata = $event->getMetadata();
49
        $metadata->addFieldMapping(
50
            self::CREATED,
51
            [
52
                'encoding' => 'system_localized',
53
                'property' => self::CREATED,
54
            ]
55
        );
56
        $metadata->addFieldMapping(
57
            self::CHANGED,
58
            [
59
                'encoding' => 'system_localized',
60
                'property' => self::CHANGED,
61
            ]
62
        );
63
    }
64
65
    /**
66
     * @param PersistEvent $event
67
     */
68
    public function handlePersist(PersistEvent $event)
69
    {
70
        $document = $event->getDocument();
71
72
        if (!$document instanceof TimestampBehavior) {
73
            return;
74
        }
75
76
        $locale = $event->getLocale();
77
78
        if (!$locale) {
79
            return;
80
        }
81
82
        if (!$document->getCreated()) {
83
            $event->getAccessor()->set(self::CREATED, new \DateTime());
84
        }
85
86
        $event->getAccessor()->set(self::CHANGED, new \DateTime());
87
    }
88
}
89