Completed
Push — master ( 6a6cfd...7dcbe1 )
by Vitaly
02:35
created

Tree::output()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 21
Code Lines 9

Duplication

Lines 7
Ratio 33.33 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 7
loc 21
ccs 12
cts 12
cp 1
rs 8.7624
cc 6
eloc 9
nc 16
nop 3
crap 6
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 \DOMNode Pointer to current dom element */
62 1
        $dom = new \DOMDocument();
63 1
        $dom->loadHTML($source);
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)) {
84
                // Get node classes
85 1
                $classes = array_filter(explode(' ', $this->getDOMAttributeValue($child, 'class')));
86
87
                // Define less node selector
88 1
                $selector = $tag;
89 1
                if (($identifier = $this->getDOMAttributeValue($child, 'id')) !== null) {
90 1
                    $selector = '#' . $identifier;
91 1
                } elseif (count($classes)) {
92
                    $selector = '.' . array_shift($classes);
93 1
                } elseif (($name = $this->getDOMAttributeValue($child, 'name')) !== null) {
94
                    $selector = $tag . '[name=' . $name . ']';
95
                }
96
97
                // Find child node by selector
98 1
                $node = $parent->getChild($selector);
99
100
                // Check if we have created this selector LessNode for this branch
101 1
                if (null === $node) {
102
                    // Create internal node instance
103 1
                    $node = new Node($selector, $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...
104 1
                }
105
106
                // Create inner class modifiers for parent node
107 1
                foreach ($classes as $class) {
108 1
                    new Node('&.' . $class, $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...
109 1
                }
110
111
                // Go deeper in recursion
112 1
                $this->analyzeSourceNode($child, $node);
113 1
            }
114 1
        }
115
116 1
        return $parent;
117
    }
118
119
    /**
120
     * Get DOM node attribute value.
121
     *
122
     * @param \DOMNode $domNode
123
     * @param string   $attributeName
124
     *
125
     * @return null|string DOM node attribute value
126
     */
127 1
    protected function getDOMAttributeValue(\DOMNode $domNode, $attributeName)
128
    {
129 1
        if (null !== $domNode->attributes) {
130
            /**@var \DOMNode $attribute */
131 1
            foreach ($domNode->attributes as $attribute) {
132 1
                $value = trim($attribute->nodeValue);
133
                // If DOM attribute matches needed
134 1
                if ($attributeName === $attribute->name && $value !== '') {
135
                    // Remove white spaces
136 1
                    return $value;
137
                }
138 1
            }
139 1
        }
140
141 1
        return null;
142
    }
143
144
    /**
145
     * @param Node   $node
146
     * @param string $output
147
     * @param int    $level
148
     *
149
     * @return string
150
     */
151 1
    public function output(Node $node, &$output = '', $level = 0)
152
    {
153
        // Define if this is not empty node and this is not generic nodes
154 1
        $hasSelector = isset($node->selector{0}) && !in_array($node->selector, array('html', 'body'));
155
156
        // Output less node with spaces
157 1 View Code Duplication
        if ($hasSelector) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
158 1
            $output .= implode('', array_fill(0, $level, '  ')) . $node . ' {' . "\n";
159 1
        }
160
161 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...
162 1
            $this->output($child, $output, $hasSelector ? $level + 1 : $level);
163 1
        }
164
165
        // Close less node with spaces
166 1 View Code Duplication
        if ($hasSelector) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
167 1
            $output .= implode('', array_fill(0, $level, '  ')) . '}' . "\n";
168 1
        }
169
170 1
        return $output;
171
    }
172
}
173