Completed
Push — master ( 7dcbe1...a91f05 )
by Vitaly
02:09
created

Tree::spaces()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
namespace samsonframework\html2less;
3
4
/**
5
 * Created by Vitaly Iegorov <[email protected]>.
6
 * on 15.04.16 at 12:43
7
 */
8
class Tree
9
{
10
    /** @var array Collection of ignored DOM nodes */
11
    public static $ignoredNodes = array(
12
        'head',
13
        'meta',
14
        'script',
15
        'noscript',
16
        'link',
17
        'title',
18
        'br',
19
    );
20
21
    /**
22
     * Build destination code tree from source code.
23
     *
24
     * @param string $source Source code
25
     *
26
     * @return Node Less tree root node
27
     */
28 1
    public function build($source)
29
    {
30
        // Prepare source code
31 1
        $source = $this->prepare($source);
32
33
        // Build destination node tree
34 1
        return $this->analyze($source);
35
    }
36
37
    /**
38
     * Source code cleaner.
39
     *
40
     * @param string $source
41
     *
42
     * @return string Cleared source code
43
     */
44 1
    protected function prepare($source)
45
    {
46
        // Remove all PHP code from view
47 1
        return trim(preg_replace('/<\?(php|=).*?\?>/', '', $source));
48
    }
49
50
    /**
51
     * Analyze source code and create destination code tree.
52
     *
53
     * @param string $source Source code
54
     *
55
     * @return Node Internal code tree
56
     */
57 1
    protected function &analyze($source)
58
    {
59 1
        libxml_use_internal_errors(true);
60
61
        /** @var \DOMDocument $dom Pointer to current dom element */
62 1
        $dom = new \DOMDocument();
63 1
        $dom->loadHTML($source, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
64
65
        // Perform recursive node analysis
66 1
        return $this->analyzeSourceNode($dom, new Node('', ''));
67
    }
68
69
    /**
70
     * Perform source node analysis.
71
     *
72
     * @param \DOMNode $domNode
73
     * @param Node     $parent
74
     *
75
     * @return Node
76
     */
77 1
    protected function &analyzeSourceNode(\DOMNode $domNode, Node $parent)
78
    {
79 1
        foreach ($domNode->childNodes as $child) {
80 1
            $tag = $child->nodeName;
81
82
            // Work only with allowed DOMElements
83 1
            if ($child->nodeType === 1 && !in_array($tag, static::$ignoredNodes, true)) {
84
                // Get node classes
85 1
                $classes = array_filter(explode(' ', $this->getDOMAttributeValue($child, 'class')));
86
87 1
                $selector = $this->getSelector($child, $tag);
88
89
                // Find child node by selector
90 1
                $node = $parent !== null ? $parent->getChild($selector) : null;
91
92
                // Check if we have created this selector LessNode for this branch
93 1
                if (null === $node) {
94
                    // Create internal node instance
95 1
                    $node = new Node($selector, $tag, $parent);
0 ignored issues
show
Documentation introduced by
$parent is of type object<samsonframework\html2less\Node>, but the function expects a null|object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
96 1
                }
97
98
                // Create inner class modifiers for parent node
99 1
                foreach ($classes as $class) {
100 1
                    new Node('&.' . $class, $tag, $node);
0 ignored issues
show
Documentation introduced by
$node is of type object<samsonframework\html2less\Node>, but the function expects a null|object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
101 1
                }
102
103
                // Go deeper in recursion
104 1
                $this->analyzeSourceNode($child, $node);
105 1
            }
106 1
        }
107
108 1
        if (null !== $parent) {
109
            /** @var Node[string] $tagNodes Group current level nodes by tags */
0 ignored issues
show
Documentation introduced by
The doc-type Node[string] could not be parsed: Expected "]" at position 2, but found "string". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
110 1
            $tagNodes = [];
111 1
            foreach ($parent->children as $child) {
0 ignored issues
show
Bug introduced by
The expression $parent->children of type object<samsonframework\html2less\Node> is not traversable.
Loading history...
112 1
                $tagNodes[$child->tag][$child->selector] = $child;
113 1
            }
114
115
            // Check if we have inner nodes with same tag
116 1
            foreach ($tagNodes as $tag => $nodes) {
117 1
                if (count($nodes) > 1) {
118 1
                    $tagNode = new Node($tag, $tag, $parent);
0 ignored issues
show
Documentation introduced by
$parent is of type object<samsonframework\html2less\Node>, but the function expects a null|object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
119 1
                    foreach ($nodes as $selector => $child) {
120
                        /**
121
                         * If we already had LESS node for this tag then we have
122
                         * already replaced it with group tag so we do not need
123
                         * to re-remove it from parent as it is already a new one
124
                         */
125 1
                        if ($selector !== $tag) {
126
                            // Attach child to new grouped tag node
127 1
                            $child->parent = &$tagNode;
128 1
                            $tagNode->children[$selector] = $child;
129
                            // Append & for inner nodes
130 1
                            $child->selector = '&' . $child->selector;
131
                            // Remove child from current parent
132 1
                            unset($parent->children[$selector]);
133 1
                        }
134 1
                    }
135 1
                }
136 1
            }
137 1
        }
138
139 1
        return $parent;
140
    }
141
142
    /**
143
     * Get DOM node attribute value.
144
     *
145
     * @param \DOMNode $domNode
146
     * @param string   $attributeName
147
     *
148
     * @return null|string DOM node attribute value
149
     */
150 1
    protected function getDOMAttributeValue(\DOMNode $domNode, $attributeName)
151
    {
152 1
        if (null !== $domNode->attributes) {
153
            /**@var \DOMAttr $attribute */
154 1
            foreach ($domNode->attributes as $attribute) {
155 1
                $value = trim($attribute->nodeValue);
156
                // If DOM attribute matches needed
157 1
                if ($attributeName === $attribute->name && $value !== '') {
158
                    // Remove white spaces
159 1
                    return $value;
160
                }
161 1
            }
162 1
        }
163
164 1
        return null;
165
    }
166
167
    /**
168
     * Get current \DOMNode LESS selector.
169
     *
170
     * @param \DOMNode $child
171
     * @param string   $tag
172
     * @param array    $classes
173
     *
174
     * @return string LESS selector
175
     */
176 1
    protected function getSelector(\DOMNode $child, $tag, array $classes = array())
177
    {
178
        // Define less node selector
179 1
        if (($identifier = $this->getDOMAttributeValue($child, 'id')) !== null) {
180 1
            return '#' . $identifier;
181 1
        } elseif (count($classes)) {
182
            return '.' . array_shift($classes);
183 1
        } elseif (($name = $this->getDOMAttributeValue($child, 'name')) !== null) {
184
            return $tag . '[name=' . $name . ']';
185
        } else {
186 1
            return $tag;
187
        }
188
    }
189
190
    /**
191
     * Render LESS tree. This function is recursive.
192
     *
193
     * @param Node   $node   Current LESS tree node
194
     * @param string $output Final LESS code string
195
     * @param int    $level  Current recursion level
196
     *
197
     * @return string LESS code
198
     */
199 1
    public function output(Node $node, $output = '', $level = 0)
200
    {
201
        // Output less node with spaces
202 1
        $output .= $this->spaces($level) . $node . '{' . "\n";
203
204 1
        foreach ($node->children as $child) {
0 ignored issues
show
Bug introduced by
The expression $node->children of type object<samsonframework\html2less\Node> is not traversable.
Loading history...
205 1
            $output = $this->output($child, $output, $level + 1);
206 1
        }
207
208
        // Close less node with spaces
209 1
        $output .= $this->spaces($level) . '}' . "\n";
210
211 1
        return $output;
212
    }
213
214
    /**
215
     * Get spaces for LESS tree level.
216
     *
217
     * @param int $level LESS tree depth
218
     *
219
     * @return string Spaces for current LESS tree depth
220
     */
221 1
    protected function spaces($level = 0)
222
    {
223 1
        return implode('', array_fill(0, $level, '  '));
224
    }
225
}
226