CustomNamespaceSubscriber::__construct()   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
namespace Goetas\Twital\EventSubscriber;
3
4
use Goetas\Twital\EventDispatcher\CompilerEvents;
5
use Goetas\Twital\EventDispatcher\SourceEvent;
6
use Goetas\Twital\EventDispatcher\TemplateEvent;
7
use Goetas\Twital\Helper\DOMHelper;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
10
/**
11
 *
12
 * @author Asmir Mustafic <[email protected]>
13
 *
14
 */
15
class CustomNamespaceSubscriber implements EventSubscriberInterface
16
{
17
    protected $customNamespaces = array();
18
19 25
    public function __construct(array $customNamespaces)
20
    {
21 25
        $this->customNamespaces = $customNamespaces;
22 25
    }
23
24 25
    public static function getSubscribedEvents()
25
    {
26
        return array(
27 25
            CompilerEvents::POST_LOAD => 'addCustomNamespace',
28 25
            CompilerEvents::POST_DUMP => 'removeCustomNamespaces',
29 25
        );
30
    }
31
32 24
    public function addCustomNamespace(TemplateEvent $event)
33
    {
34 24
        foreach (iterator_to_array($event->getTemplate()->getDocument()->childNodes) as $child) {
35 24
            if ($child instanceof \DOMElement) {
36 24
                DOMHelper::checkNamespaces($child, $this->customNamespaces);
37 24
            }
38 24
        }
39 24
    }
40
41 24
    public function removeCustomNamespaces(SourceEvent $event)
42
    {
43 24
        $template = $event->getTemplate();
44 24
        foreach ($this->customNamespaces as $prefix => $ns) {
45 24
            $template = preg_replace('#<(.*) xmlns:' . $prefix . '="' . $ns . '"(.*)>#mi', "<\\1\\2>", $template);
46 24
        }
47 24
        $event->setTemplate($template);
48 24
    }
49
}
50