1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ortic\Css2Less; |
4
|
|
|
|
5
|
|
|
use Ortic\Css2Less\tokens\LessRuleList; |
6
|
|
|
use Ortic\Css2Less\tokens\LessRule; |
7
|
|
|
|
8
|
|
|
class Css2Less |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var string $cssContent |
12
|
|
|
*/ |
13
|
|
|
protected $cssContent; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var \CssParser $parser |
17
|
|
|
*/ |
18
|
|
|
protected $parser; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Create a new parser object, use parameter to specify CSS you |
22
|
|
|
* wish to convert into a LESS file |
23
|
|
|
* |
24
|
|
|
* @param string $cssContent |
25
|
|
|
*/ |
26
|
9 |
|
public function __construct($cssContent) |
27
|
|
|
{ |
28
|
9 |
|
$this->cssContent = $cssContent; |
29
|
9 |
|
$this->parser = new \CssParser($this->cssContent); |
30
|
9 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Returns a string containing the LESS content matching the CSS input |
34
|
|
|
* @return string |
35
|
|
|
*/ |
36
|
9 |
|
public function getLess() |
37
|
|
|
{ |
38
|
9 |
|
$lessTree = array(); |
39
|
|
|
|
40
|
|
|
// this variable is true, if we're within a ruleset, e.g. p { .. here .. } |
41
|
|
|
// we have to normalize them |
42
|
9 |
|
$withinRulset = false; |
43
|
9 |
|
$ruleSet = null; |
44
|
9 |
|
$ruleSetList = new LessRuleList(); |
45
|
|
|
|
46
|
9 |
|
$tokens = $this->parser->getTokens(); |
47
|
|
|
|
48
|
9 |
|
foreach ($tokens as $token) { |
49
|
|
|
// we have to skip some tokens, their information is redundant |
50
|
9 |
|
if ($token instanceof \CssAtMediaStartToken || |
51
|
9 |
|
$token instanceof \CssAtMediaEndToken |
52
|
|
|
) { |
53
|
1 |
|
continue; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// we have to build a hierarchy with CssRulesetStartToken, CssRulesetEndToken |
57
|
9 |
|
if ($token instanceof \CssRulesetStartToken) { |
58
|
9 |
|
$withinRulset = true; |
59
|
9 |
|
$ruleSet = new LessRule($token->Selectors); |
60
|
|
|
} elseif ($token instanceof \CssRulesetEndToken) { |
61
|
9 |
|
$withinRulset = false; |
62
|
9 |
|
if ($ruleSet) { |
63
|
9 |
|
$ruleSetList->addRule($ruleSet); |
64
|
|
|
} |
65
|
9 |
|
$ruleSet = null; |
66
|
|
|
} else { |
67
|
|
|
// as long as we're in a ruleset, we're adding all token to a custom array |
68
|
|
|
// this will be lessified once we've found CssRulesetEndToken and then added |
69
|
|
|
// to the actual $lessTree variable |
70
|
9 |
|
if ($withinRulset) { |
71
|
9 |
|
$ruleSet->addToken($token); |
72
|
|
|
} else { |
73
|
9 |
|
$lessTree[] = $token; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
9 |
|
$return = ''; |
79
|
9 |
|
foreach ($lessTree as $node) { |
80
|
|
|
// @TODO this format method shouldn't be in this class.. |
81
|
1 |
|
$return .= $ruleSetList->formatTokenAsLess($node) . "\n"; |
82
|
|
|
} |
83
|
|
|
|
84
|
9 |
|
$return .= $ruleSetList->lessify(); |
85
|
|
|
|
86
|
9 |
|
return $return; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
} |
|
|
|
|
90
|
|
|
|
Below you find some examples: