StopwatchEventSubscriber   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 8
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 50
ccs 17
cts 19
cp 0.8947
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 7 1
A __construct() 0 4 1
A onPreSerialize() 0 9 3
A onPostSerialize() 0 9 3
1
<?php
2
3
namespace JMS\SerializerBundle\Serializer;
4
5
use JMS\Serializer\EventDispatcher\Events;
6
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
7
use JMS\Serializer\EventDispatcher\ObjectEvent;
8
9
/**
10
 * @author Adrien Brault <[email protected]>
11
 */
12
class StopwatchEventSubscriber implements EventSubscriberInterface
13
{
14
    /**
15
     * {@inheritdoc}
16
     */
17 25
    public static function getSubscribedEvents()
18
    {
19
        return array(
20 25
            array('event' => Events::PRE_SERIALIZE, 'method' => 'onPreSerialize', 'priority' => -1000),
21 25
            array('event' => Events::POST_SERIALIZE, 'method' => 'onPostSerialize', 'priority' => 1000),
22 25
        );
23
    }
24
25
    /**
26
     * A stopwatch object which exposes a start($name) and a stop($name) method.
27
     *
28
     * @var object
29
     */
30
    private $stopwatch;
31
32
    /**
33
     * @var object
34
     */
35
    private $rootObject;
36
37 5
    public function __construct($stopwatch)
38
    {
39 5
        $this->stopwatch = $stopwatch;
40 5
    }
41
42 5
    public function onPreSerialize(ObjectEvent $event)
43
    {
44 5
        if ($event->getContext()->getDepth() > 1 || null !== $this->rootObject) {
45
            return;
46
        }
47
48 5
        $this->stopwatch->start('jms_serializer');
49 5
        $this->rootObject = $event->getObject();
50 5
    }
51
52 3
    public function onPostSerialize(ObjectEvent $event)
53
    {
54 3
        if (null === $this->rootObject || $event->getObject() !== $this->rootObject) {
55
            return;
56
        }
57
58 3
        $this->stopwatch->stop('jms_serializer');
59 3
        $this->rootObject = null;
60 3
    }
61
}
62