Completed
Pull Request — master (#44)
by Asmir
18:26 queued 08:25
created

ExtendsAttribute   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
cbo 2
dl 0
loc 49
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C visit() 0 46 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
    public function visit(\DOMAttr $att, Compiler $context)
15
    {
16
        $node = $att->ownerElement;
17
18
        $filename = '"' . $att->value . '"';
19
20
21
        $xp = new \DOMXPath($att->ownerDocument);
22
        $xp->registerNamespace("t", Twital::NS);
23
24
        $candidates = [];
25
        foreach ($xp->query(".//*[@t:block-inner or @t:block-outer]|.//t:*", $node) as $blockNode) {
26
27
            $ancestors = $xp->query("ancestor::*[@t:block-inner or @t:block-outer or @t:extends]", $blockNode);
28
29
            if ($ancestors->length === 1) {
30
                $candidates[] = $blockNode;
31
            }
32
        }
33
34
        foreach ($candidates as $candidate) {
35
            if ($candidate->parentNode !== $node) {
36
                $candidate->parentNode->removeChild($candidate);
37
                $node->appendChild($candidate);
38
            }
39
        }
40
        if ($candidates) {
41
            foreach (iterator_to_array($node->childNodes) as $k => $item) {
42
                if (!in_array($item, $candidates, true)) {
43
                    $node->removeChild($item);
44
                }
45
            }
46
        }
47
48
        $context->compileChilds($node);
49
50
        $set = iterator_to_array($node->childNodes);
51
        if (count($set)) {
52
            $n = $node->ownerDocument->createTextNode("\n");
53
            array_unshift($set, $n);
54
        }
55
        $ext = $context->createControlNode("extends {$filename}");
56
        array_unshift($set, $ext);
57
58
        DOMHelper::replaceWithSet($node, $set);
59
    }
60
}
61