Completed
Push — twig-2 ( 00bf9b...3d05b1 )
by Asmir
05:31
created

ExtendsAttribute::visit()   C

Complexity

Conditions 9
Paths 36

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 9

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 46
ccs 35
cts 35
cp 1
rs 5.0942
cc 9
eloc 26
nc 36
nop 2
crap 9
1
<?php
2
namespace Goetas\Twital\Attribute;
3
4
use Goetas\Twital\Attribute as AttributeBase;
5
use Goetas\Twital\Compiler;
6
use Goetas\Twital\Helper\DOMHelper;
7
use Goetas\Twital\Twital;
8
9
/**
10
 * @author Asmir Mustafic <[email protected]>
11
 */
12
class ExtendsAttribute implements AttributeBase
13
{
14 9
    public function visit(\DOMAttr $att, Compiler $context)
15
    {
16 9
        $node = $att->ownerElement;
17
18 9
        $filename = '"' . $att->value . '"';
19
20
21 9
        $xp = new \DOMXPath($att->ownerDocument);
22 9
        $xp->registerNamespace("t", Twital::NS);
23
24 9
        $candidates = [];
25 9
        foreach ($xp->query(".//*[@t:block-inner or @t:block-outer]|.//t:*", $node) as $blockNode) {
26
27 9
            $ancestors = $xp->query("ancestor::*[@t:block-inner or @t:block-outer or @t:extends]", $blockNode);
28
29 9
            if ($ancestors->length === 1) {
30 9
                $candidates[] = $blockNode;
31 9
            }
32 9
        }
33
34 9
        foreach ($candidates as $candidate) {
35 9
            if ($candidate->parentNode !== $node) {
36 9
                $candidate->parentNode->removeChild($candidate);
37 9
                $node->appendChild($candidate);
38 9
            }
39 9
        }
40 9
        if ($candidates) {
41 9
            foreach (iterator_to_array($node->childNodes) as $k => $item) {
42 9
                if (!in_array($item, $candidates, true)) {
43 9
                    $node->removeChild($item);
44 9
                }
45 9
            }
46 9
        }
47
48 9
        $context->compileChilds($node);
49
50 9
        $set = iterator_to_array($node->childNodes);
51 9
        if (count($set)) {
52 9
            $n = $node->ownerDocument->createTextNode("\n");
53 9
            array_unshift($set, $n);
54 9
        }
55 9
        $ext = $context->createControlNode("extends {$filename}");
56 9
        array_unshift($set, $ext);
57
58 9
        DOMHelper::replaceWithSet($node, $set);
59 9
    }
60
}
61