IDNodeSubscriber::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 15
c 0
b 0
f 0
ccs 8
cts 8
cp 1
rs 9.7666
cc 1
nc 1
nop 0
crap 1
1
<?php
2
namespace Goetas\Twital\EventSubscriber;
3
4
use Goetas\Twital\EventDispatcher\CompilerEvents;
5
use Goetas\Twital\EventDispatcher\TemplateEvent;
6
use Goetas\Twital\Twital;
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
9
/**
10
 *
11
 * @author Asmir Mustafic <[email protected]>
12
 *
13
 */
14
class IDNodeSubscriber implements EventSubscriberInterface
15
{
16 487
    public static function getSubscribedEvents()
17
    {
18
        return array(
19 487
            CompilerEvents::POST_LOAD => array(
20
                array(
21
                    'addAttribute'
22 487
                )
23 487
            ),
24 487
            CompilerEvents::PRE_DUMP => array(
25
                array(
26
                    'removeAttribute'
27 487
                )
28 487
            )
29 487
        );
30
    }
31
32 486
    public function addAttribute(TemplateEvent $event)
33
    {
34 486
        $doc = $event->getTemplate()->getDocument();
35 486
        $xp = new \DOMXPath($doc);
36
        /**
37
         * @var \DOMElement[] $nodes
38
         */
39 486
        $nodes = $xp->query("//*[@*[namespace-uri()='" . Twital::NS . "']]");
40 486
        foreach ($nodes as $node) {
41 66
            $node->setAttributeNS(Twital::NS, '__internal-id__', microtime(1) . mt_rand());
42 486
        }
43 486
    }
44
45 484
    public function removeAttribute(TemplateEvent $event)
46
    {
47 484
        $doc = $event->getTemplate()->getDocument();
48 484
        $xp = new \DOMXPath($doc);
49 484
        $xp->registerNamespace('twital', Twital::NS);
50 484
        $attributes = $xp->query("//@twital:__internal-id__");
51 484
        foreach ($attributes as $attribute) {
52 3
            $attribute->ownerElement->removeAttributeNode($attribute);
53 484
        }
54 484
    }
55
}
56