forked from MyIntervals/PHP-CSS-Parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSSParser.php
executable file
·503 lines (468 loc) · 14 KB
/
CSSParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
<?php
require_once('lib/CSSProperties.php');
require_once('lib/CSSList.php');
require_once('lib/CSSRuleSet.php');
require_once('lib/CSSRule.php');
require_once('lib/CSSValue.php');
require_once('lib/CSSValueList.php');
/**
* @package html
* CSSParser class parses CSS from text into a data structure.
*/
class CSSParser {
private $sText;
private $iCurrentPosition;
private $iLength;
public function __construct($sText, $sDefaultCharset = 'utf-8') {
$this->sText = $sText;
$this->iCurrentPosition = 0;
$this->setCharset($sDefaultCharset);
}
public function setCharset($sCharset) {
$this->sCharset = $sCharset;
$this->iLength = mb_strlen($this->sText, $this->sCharset);
}
public function getCharset() {
return $this->sCharset;
}
public function parse() {
$oResult = new CSSDocument();
$this->parseDocument($oResult);
return $oResult;
}
private function parseDocument(CSSDocument $oDocument) {
$this->consumeWhiteSpace();
$this->parseList($oDocument, true);
}
private function parseList(CSSList $oList, $bIsRoot = false) {
while(!$this->isEnd()) {
if($this->comes('@')) {
$oList->append($this->parseAtRule());
} else if($this->comes('}')) {
$this->consume('}');
if($bIsRoot) {
throw new Exception("Unopened {");
} else {
return;
}
} else {
$oList->append($this->parseSelector());
}
$this->consumeWhiteSpace();
}
if(!$bIsRoot) {
throw new Exception("Unexpected end of document");
}
}
private function parseAtRule() {
$this->consume('@');
$sIdentifier = $this->parseIdentifier();
$this->consumeWhiteSpace();
if($sIdentifier === 'media') {
$oResult = new CSSMediaQuery();
$oResult->setQuery(trim($this->consumeUntil('{')));
$this->consume('{');
$this->consumeWhiteSpace();
$this->parseList($oResult);
return $oResult;
} else if($sIdentifier === 'import') {
$oLocation = $this->parseURLValue();
$this->consumeWhiteSpace();
$sMediaQuery = null;
if(!$this->comes(';')) {
$sMediaQuery = $this->consumeUntil(';');
}
$this->consume(';');
return new CSSImport($oLocation, $sMediaQuery);
} else if($sIdentifier === 'charset') {
$sCharset = $this->parseStringValue();
$this->consumeWhiteSpace();
$this->consume(';');
$this->setCharset($sCharset->getString());
return new CSSCharset($sCharset);
} else {
//Unknown other at rule (font-face or such)
$this->consume('{');
$this->consumeWhiteSpace();
$oAtRule = new CSSAtRule($sIdentifier);
$this->parseRuleSet($oAtRule);
return $oAtRule;
}
}
/**
* This has been modified to allow for Origin functions as identifiers
*/
private function parseIdentifier($bAllowFunctions = true) {
$sResult = $this->parseCharacter(true);
if($sResult === null) {
throw new Exception("Identifier expected, got {$this->peek(5)}");
}
$sCharacter;
while(($sCharacter = $this->parseCharacter(true)) !== null) {
$sResult .= $sCharacter;
}
if($bAllowFunctions && $this->comes('(')) {
$this->consume('(');
$sResult = new CSSFunction($sResult, $this->parseValue(array('=', ',')));
$this->consume(')');
}
return $sResult;
}
private function parseStringValue() {
$sBegin = $this->peek();
$sQuote = null;
if($sBegin === "'") {
$sQuote = "'";
} else if($sBegin === '"') {
$sQuote = '"';
}
if($sQuote !== null) {
$this->consume($sQuote);
}
$sResult = "";
$sContent = null;
if($sQuote === null) {
//Unquoted strings end in whitespace or with braces, brackets, parentheses
while(!preg_match('/[\\s{}()<>\\[\\]]/isu', $this->peek())) {
$sResult .= $this->parseCharacter(false);
}
} else {
while(!$this->comes($sQuote)) {
$sContent = $this->parseCharacter(false);
if($sContent === null) {
throw new Exception("Non-well-formed quoted string {$this->peek(3)}");
}
$sResult .= $sContent;
}
$this->consume($sQuote);
}
return new CSSString($sResult);
}
private function parseOriginVariable() {
$this->consume('$');
$sValue = $this->parseIdentifier(false);
return new CSSOriginVariable($sValue);
}
private function parseOriginFunction() {
$this->consume('@');
// Get the function name
$fName = $this->parseIdentifier(false);
$this->consume('(');
$result = new CSSOriginFunction($fName, $this->parseValue(array('=', ',')));
$this->consume(')');
return $result;
}
private function parseCharacter($bIsForIdentifier) {
if($this->peek() === '\\') {
$this->consume('\\');
if($this->comes('\n') || $this->comes('\r')) {
return '';
}
$aMatches;
if(preg_match('/[0-9a-fA-F]/Su', $this->peek()) === 0) {
return $this->consume(1);
}
$sUnicode = $this->consumeExpression('/^[0-9a-fA-F]{1,6}/u');
if(mb_strlen($sUnicode, $this->sCharset) < 6) {
//Consume whitespace after incomplete unicode escape
if(preg_match('/\\s/isSu', $this->peek())) {
if($this->comes('\r\n')) {
$this->consume(2);
} else {
$this->consume(1);
}
}
}
$iUnicode = intval($sUnicode, 16);
$sUtf32 = "";
for($i=0;$i<4;$i++) {
$sUtf32 .= chr($iUnicode & 0xff);
$iUnicode = $iUnicode >> 8;
}
return iconv('utf-32le', $this->sCharset, $sUtf32);
}
if($bIsForIdentifier) {
// We modified this to allow $section->name variables inside CSS functions
if(preg_match('/[a-zA-Z0-9\>\$]|-|_/u', $this->peek()) === 1) {
return $this->consume(1);
} else if(ord($this->peek()) > 0xa1) {
return $this->consume(1);
} else {
return null;
}
} else {
return $this->consume(1);
}
// Does not reach here
return null;
}
private function parseSelector() {
$oResult = new CSSDeclarationBlock();
$oResult->setSelector($this->consumeUntil('{'));
$this->consume('{');
$this->consumeWhiteSpace();
$this->parseRuleSet($oResult);
return $oResult;
}
private function parseRuleSet($oRuleSet) {
while(!$this->comes('}')) {
$oRuleSet->addRule($this->parseRule());
$this->consumeWhiteSpace();
}
$this->consume('}');
}
private function parseRule() {
// A rule can also be an origin function
if($this->comes('@')){
$this->consume('@');
$fName = $this->parseIdentifier(false);
$this->consume('(');
$result = new CSSOriginFunction($fName, $this->parseValue(array('=', ',')));
$this->consume(')');
if($this->comes(';')) $this->consume(';');
return $result;
}
$oRule = new CSSRule($this->parseIdentifier());
$this->consumeWhiteSpace();
$this->consume(':');
$oValue = $this->parseValue(self::listDelimiterForRule($oRule->getRule()));
$oRule->setValue($oValue);
if($this->comes('!')) {
$this->consume('!');
$this->consumeWhiteSpace();
$sImportantMarker = $this->consume(strlen('important'));
if(mb_convert_case($sImportantMarker, MB_CASE_LOWER) !== 'important') {
throw new Exception("! was followed by “".$sImportantMarker."”. Expected “important”");
}
$oRule->setIsImportant(true);
}
if($this->comes(';')) {
$this->consume(';');
}
return $oRule;
}
private function parseValue($aListDelimiters) {
$aStack = array();
$this->consumeWhiteSpace();
while(!($this->comes('}') || $this->comes(';') || $this->comes('!') || $this->comes(')'))) {
if(count($aStack) > 0) {
$bFoundDelimiter = false;
foreach($aListDelimiters as $sDelimiter) {
if($this->comes($sDelimiter)) {
array_push($aStack, $this->consume($sDelimiter));
$this->consumeWhiteSpace();
$bFoundDelimiter = true;
break;
}
}
if(!$bFoundDelimiter) {
//Whitespace was the list delimiter
array_push($aStack, ' ');
}
}
array_push($aStack, $this->parsePrimitiveValue());
$this->consumeWhiteSpace();
}
foreach($aListDelimiters as $sDelimiter) {
if(count($aStack) === 1) {
return $aStack[0];
}
$iStartPosition = null;
while(($iStartPosition = array_search($sDelimiter, $aStack, true)) !== false) {
$iLength = 2; //Number of elements to be joined
for($i=$iStartPosition+2;$i<count($aStack);$i+=2) {
if($sDelimiter !== $aStack[$i]) {
break;
}
$iLength++;
}
$oList = new CSSRuleValueList($sDelimiter);
for($i=$iStartPosition-1;$i-$iStartPosition+1<$iLength*2;$i+=2) {
$oList->addListComponent($aStack[$i]);
}
array_splice($aStack, $iStartPosition-1, $iLength*2-1, array($oList));
}
}
return $aStack[0];
}
private static function listDelimiterForRule($sRule) {
if(preg_match('/^font($|-)/', $sRule)) {
return array(',', '/', ' ');
}
return array(',', ' ', '/');
}
private function parsePrimitiveValue() {
$oValue = null;
$this->consumeWhiteSpace();
if(is_numeric($this->peek()) || (($this->comes('-') || $this->comes('.')) && is_numeric($this->peek(1, 1)))) {
$oValue = $this->parseNumericValue();
} else if($this->comes('#') || $this->comes('rgb') || $this->comes('hsl')) {
$oValue = $this->parseColorValue();
} else if($this->comes('url')){
$oValue = $this->parseURLValue();
} else if($this->comes("'") || $this->comes('"')){
$oValue = $this->parseStringValue();
} else if($this->comes('$')) {
// This is part of the custom origin variable parsing
$oValue = $this->parseOriginVariable();
} else if($this->comes('@')) {
$oValue = $this->parseOriginFunction();
} else {
$oValue = $this->parseIdentifier();
}
$this->consumeWhiteSpace();
return $oValue;
}
private function parseNumericValue($bForColor = false) {
$sSize = '';
if($this->comes('-')) {
$sSize .= $this->consume('-');
}
while(is_numeric($this->peek()) || $this->comes('.')) {
if($this->comes('.')) {
$sSize .= $this->consume('.');
} else {
$sSize .= $this->consume(1);
}
}
$fSize = floatval($sSize);
$sUnit = null;
if($this->comes('%')) {
$sUnit = $this->consume('%');
} else if($this->comes('em')) {
$sUnit = $this->consume('em');
} else if($this->comes('ex')) {
$sUnit = $this->consume('ex');
} else if($this->comes('px')) {
$sUnit = $this->consume('px');
} else if($this->comes('deg')) {
$sUnit = $this->consume('deg');
} else if($this->comes('s')) {
$sUnit = $this->consume('s');
} else if($this->comes('cm')) {
$sUnit = $this->consume('cm');
} else if($this->comes('pt')) {
$sUnit = $this->consume('pt');
} else if($this->comes('in')) {
$sUnit = $this->consume('in');
} else if($this->comes('pc')) {
$sUnit = $this->consume('pc');
} else if($this->comes('cm')) {
$sUnit = $this->consume('cm');
} else if($this->comes('mm')) {
$sUnit = $this->consume('mm');
}
return new CSSSize($fSize, $sUnit, $bForColor);
}
private function parseColorValue() {
$aColor = array();
if($this->comes('#')) {
$this->consume('#');
$sValue = $this->parseIdentifier(false);
if(mb_strlen($sValue, $this->sCharset) === 3) {
$sValue = $sValue[0].$sValue[0].$sValue[1].$sValue[1].$sValue[2].$sValue[2];
}
$aColor = array('r' => new CSSSize(intval($sValue[0].$sValue[1], 16), null, true), 'g' => new CSSSize(intval($sValue[2].$sValue[3], 16), null, true), 'b' => new CSSSize(intval($sValue[4].$sValue[5], 16), null, true));
} else {
$sColorMode = $this->parseIdentifier(false);
$this->consumeWhiteSpace();
$this->consume('(');
$iLength = mb_strlen($sColorMode, $this->sCharset);
for($i=0;$i<$iLength;$i++) {
$this->consumeWhiteSpace();
$aColor[$sColorMode[$i]] = $this->parseNumericValue(true);
$this->consumeWhiteSpace();
if($i < ($iLength-1)) {
$this->consume(',');
}
}
$this->consume(')');
}
return new CSSColor($aColor);
}
private function parseURLValue() {
$bUseUrl = $this->comes('url');
if($bUseUrl) {
$this->consume('url');
$this->consumeWhiteSpace();
$this->consume('(');
}
$this->consumeWhiteSpace();
$oResult = new CSSURL($this->parseStringValue());
if($bUseUrl) {
$this->consumeWhiteSpace();
$this->consume(')');
}
return $oResult;
}
private function comes($sString, $iOffset = 0) {
if($this->isEnd()) {
return false;
}
return $this->peek($sString, $iOffset) == $sString;
}
private function peek($iLength = 1, $iOffset = 0) {
if($this->isEnd()) {
return '';
}
if(is_string($iLength)) {
$iLength = mb_strlen($iLength, $this->sCharset);
}
if(is_string($iOffset)) {
$iOffset = mb_strlen($iOffset, $this->sCharset);
}
return mb_substr($this->sText, $this->iCurrentPosition+$iOffset, $iLength, $this->sCharset);
}
private function consume($mValue = 1) {
if(is_string($mValue)) {
$iLength = mb_strlen($mValue, $this->sCharset);
if(mb_substr($this->sText, $this->iCurrentPosition, $iLength, $this->sCharset) !== $mValue) {
throw new Exception("Expected $mValue, got ".$this->peek(5));
}
$this->iCurrentPosition += mb_strlen($mValue, $this->sCharset);
return $mValue;
} else {
if($this->iCurrentPosition+$mValue > $this->iLength) {
throw new Exception("Tried to consume $mValue chars, exceeded file end");
}
$sResult = mb_substr($this->sText, $this->iCurrentPosition, $mValue, $this->sCharset);
$this->iCurrentPosition += $mValue;
return $sResult;
}
}
private function consumeExpression($mExpression) {
$aMatches;
if(preg_match($mExpression, $this->inputLeft(), $aMatches, PREG_OFFSET_CAPTURE) === 1) {
return $this->consume($aMatches[0][0]);
}
throw new Exception("Expected pattern $mExpression not found, got: {$this->peek(5)}");
}
private function consumeWhiteSpace() {
do {
while(preg_match('/\\s/isSu', $this->peek()) === 1) {
$this->consume(1);
}
} while($this->consumeComment());
}
private function consumeComment() {
if($this->comes('/*')) {
$this->consumeUntil('*/');
$this->consume('*/');
return true;
}
return false;
}
private function isEnd() {
return $this->iCurrentPosition >= $this->iLength;
}
private function consumeUntil($sEnd) {
$iEndPos = mb_strpos($this->sText, $sEnd, $this->iCurrentPosition, $this->sCharset);
if($iEndPos === false) {
throw new Exception("Required $sEnd not found, got {$this->peek(5)}");
}
return $this->consume($iEndPos-$this->iCurrentPosition);
}
private function inputLeft() {
return mb_substr($this->sText, $this->iCurrentPosition, -1, $this->sCharset);
}
}