Completed
Push — master ( 8e0761...66491d )
by Remo
01:58
created

LessRuleList::parsePseudoClasses()   C

Complexity

Conditions 9
Paths 19

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 9

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 24
ccs 16
cts 16
cp 1
rs 5.3563
cc 9
eloc 15
nc 19
nop 1
crap 9
1
<?php
2
3
namespace Ortic\Css2Less\tokens;
4
5
/**
6
 * Class LessRuleList
7
 * @package Ortic\Css2Less\tokens
8
 */
9
class LessRuleList
10
{
11
    private $list = array();
12
13
    /**
14
     * Add a new rule object to our list
15
     * @param LessRule $rule
16
     */
17 9
    public function addRule(LessRule $rule)
18
    {
19 9
        $this->list[] = $rule;
20 9
    }
21
22
    /**
23
     * Build and returns a tree for the CSS input
24
     * @return array
25
     */
26 9
    protected function getTree()
27
    {
28 9
        $output = array();
29
30 9
        foreach ($this->list as $ruleSet) {
31 9
            $selectors = $ruleSet->getSelectors();
32
33 9
            foreach ($ruleSet->getTokens() as $token) {
34 9
                $this->parseTreeNode($output, $selectors, $token);
35 9
            }
36 9
        }
37 9
        return $output;
38
    }
39
40
    /**
41
     * Add support for direct descendants operator by aligning the spaces properly.
42
     * the code below supports "html >p" since we split by spaces. A selector "html > p" would cause an
43
     * additional tree level, we therefore normalize them with the two lines below.
44
     *
45
     * @param string $selector
46
     * @return string
47
     */
48 9
    protected function parseDirectDescendants($selector)
49
    {
50 9
        $selector = str_replace('> ', '>', $selector);
51 9
        $selector = str_replace('>', ' >', $selector);
52 9
        return $selector;
53
    }
54
55
    /**
56
     * Support for pseudo classes by adding a space before ":" and also "&" to let less know that there
57
     * shouldn't be a space when concatenating the nested selectors to a single css rule. We have to
58
     * ignore every colon if it's wrapped by :not(...) as we don't nest this in LESS.
59
     *
60
     * @param string $selector
61
     * @return string
62
     */
63 9
    protected function parsePseudoClasses($selector)
64
    {
65 9
        $nestedPseudo = false;
66 9
        $lastCharacterColon = false;
67 9
        $selectorOut = '';
68 9
        for ($i = 0; $i < strlen($selector); $i++) {
69 9
            $c = $selector{$i};
70
71
            // Don't parse anything between (..) and [..]
72 9
            $nestedPseudo = ($c === '(' || $c === '[') || $nestedPseudo;
73 9
            $nestedPseudo = !($c === ')' || $c === ']') && $nestedPseudo;
74
75 9
            if ($nestedPseudo === false && $c === ':' && $lastCharacterColon === false) {
76 3
                $selectorOut .= ' &';
77 3
                $lastCharacterColon = true;
78 3
            }
79
            else {
80 9
                $lastCharacterColon = false;
81
            }
82
83 9
            $selectorOut .= $c;
84 9
        }
85 9
        return $selectorOut;
86
    }
87
88
    /**
89
     * Parse CSS input part into a LESS node
90
     * @param $output
91
     * @param $selectors
92
     * @param $token
93
     */
94 9
    protected function parseTreeNode(&$output, $selectors, $token)
95
    {
96 9
        foreach ($token->MediaTypes as $mediaType) {
97
            // make sure we're aware of our media type
98 9
            if (!array_key_exists($mediaType, $output)) {
99 9
                $output[$mediaType] = array();
100 9
            }
101
102 9
            foreach ($selectors as $selector) {
103
                // add declaration token to output for each selector
104 9
                $currentNode = &$output[$mediaType];
105
106 9
                $selector = $this->parseDirectDescendants($selector);
107 9
                $selector = $this->parsePseudoClasses($selector);
108
109
                // selectors like "html body" must be split into an array so we can
110
                // easily nest them
111 9
                $selectorPath = preg_split('[ ]', $selector, -1, PREG_SPLIT_NO_EMPTY);
112 9
                foreach ($selectorPath as $selectorPathItem) {
113 9
                    if (!array_key_exists($selectorPathItem, $currentNode)) {
114 9
                        $currentNode[$selectorPathItem] = array();
115 9
                    }
116 9
                    $currentNode = &$currentNode[$selectorPathItem];
117 9
                }
118
119 9
                $currentNode['@rules'][] = $this->formatTokenAsLess($token);
120 9
            }
121 9
        }
122 9
    }
123
124
    /**
125
     * Format LESS nodes in a nicer way with indentation and proper brackets
126
     * @param $token
127
     * @param int $level
128
     * @return string
129
     */
130 9
    public function formatTokenAsLess(\aCssToken $token, $level = 0)
131
    {
132 9
        $indentation = str_repeat("\t", $level);
133
134 9
        if ($token instanceof \CssRulesetDeclarationToken) {
135 9
            return $indentation . $token->Property . ": " . $token->Value . ($token->IsImportant ? " !important" : "") . ($token->IsLast ? "" : ";");
136 1
        } elseif ($token instanceof \CssAtKeyframesStartToken) {
137 1
            return $indentation . "@" . $token->AtRuleName . " \"" . $token->Name . "\" {";
138 1
        } elseif ($token instanceof \CssAtKeyframesRulesetStartToken) {
139 1
            return $indentation . "\t" . implode(",", $token->Selectors) . " {";
140 1
        } elseif ($token instanceof \CssAtKeyframesRulesetEndToken) {
141 1
            return $indentation . "\t" . "}";
142 1 View Code Duplication
        } elseif ($token instanceof \CssAtKeyframesRulesetDeclarationToken) {
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...
143 1
            return $indentation . "\t\t" . $token->Property . ": " . $token->Value . ($token->IsImportant ? " !important" : "") . ($token->IsLast ? "" : ";");
144 1
        } elseif ($token instanceof \CssAtCharsetToken) {
145 1
            return $indentation . "@charset " . $token->Charset . ";";
146 1
        } elseif ($token instanceof \CssAtFontFaceStartToken) {
147 1
            return "@font-face {";
148 1 View Code Duplication
        } elseif ($token instanceof \CssAtFontFaceDeclarationToken) {
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...
149 1
            return $indentation . "\t" . $token->Property . ": " . $token->Value . ($token->IsImportant ? " !important" : "") . ($token->IsLast ? "" : ";");
150
        } else {
151 1
            return $indentation . $token;
152
        }
153
    }
154
155 9
    protected function formatAsLess($selector, $level = 0)
156
    {
157 9
        $return = '';
158 9
        $indentation = str_repeat("\t", $level);
159 9
        foreach ($selector as $nodeKey => $node) {
160 9
            $return .= $indentation . "{$nodeKey} {\n";
161
162 9
            foreach ($node as $subNodeKey => $subNodes) {
163 9
                if ($subNodeKey === '@rules') {
164 9
                    foreach ($subNodes as $subNode) {
165 9
                        $return .= $indentation . "\t" . $subNode . "\n";
166 9
                    }
167 9
                } else {
168 8
                    $return .= $this->formatAsLess(array($subNodeKey => $subNodes), $level + 1);
169
                }
170 9
            }
171
172 9
            $return .= $indentation . "}\n";
173
174 9
        }
175 9
        return $return;
176
    }
177
178 9
    public function lessify()
179
    {
180 9
        $tree = $this->getTree();
181 9
        $return = '';
182
183 9
        foreach ($tree as $mediaType => $node) {
184 9
            if ($mediaType == 'all') {
185 9
                $return .= $this->formatAsLess($node);
186 9
            } else {
187 1
                $return .= "@media {$mediaType} {\n";
188 1
                $return .= $this->formatAsLess($node, 1);
189 1
                $return .= "}\n";
190
            }
191 9
        }
192
193 9
        return $return;
194
    }
195
}
196