StopwatchEventSubscriber::onPreSerialize()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
rs 9.6666
cc 3
eloc 5
nc 2
nop 1
crap 3.0416
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