-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathRuleSet.php
More file actions
388 lines (358 loc) · 15 KB
/
Copy pathRuleSet.php
File metadata and controls
388 lines (358 loc) · 15 KB
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
<?php
declare(strict_types=1);
namespace Sabberworm\CSS\RuleSet;
use Sabberworm\CSS\Comment\CommentContainer;
use Sabberworm\CSS\CSSElement;
use Sabberworm\CSS\CSSList\CSSListItem;
use Sabberworm\CSS\OutputFormat;
use Sabberworm\CSS\Parsing\ParserState;
use Sabberworm\CSS\Parsing\UnexpectedEOFException;
use Sabberworm\CSS\Parsing\UnexpectedTokenException;
use Sabberworm\CSS\Position\Position;
use Sabberworm\CSS\Position\Positionable;
use Sabberworm\CSS\Property\Declaration;
/**
* This class is a container for individual `Declaration`s.
*
* The most common form of a rule set is one constrained by a selector, i.e., a `DeclarationBlock`.
* However, unknown `AtRule`s (like `@font-face`) are rule sets as well.
*
* If you want to manipulate a `RuleSet`, use the methods `addRule()`, `getRules()` and `removeRule()`
* (which accepts either a `Declaration` or a rule name; optionally suffixed by a dash to remove all related rules).
*
* Note that `CSSListItem` extends both `Commentable` and `Renderable`, so those interfaces must also be implemented.
*/
class RuleSet implements CSSElement, CSSListItem, Positionable, RuleContainer
{
use CommentContainer;
use Position;
/**
* the rules in this rule set, using the property name as the key,
* with potentially multiple rules per property name.
*
* @var array<string, array<int<0, max>, Declaration>>
*/
private $declarations = [];
/**
* @param int<1, max>|null $lineNumber
*/
public function __construct(?int $lineNumber = null)
{
$this->setPosition($lineNumber);
}
/**
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*
* @internal since V8.8.0
*/
public static function parseRuleSet(ParserState $parserState, RuleSet $ruleSet): void
{
while ($parserState->comes(';')) {
$parserState->consume(';');
}
while (true) {
$commentsBeforeRule = [];
$parserState->consumeWhiteSpace($commentsBeforeRule);
if ($parserState->comes('}')) {
break;
}
$declaration = null;
if ($parserState->getSettings()->usesLenientParsing()) {
try {
$declaration = Declaration::parse($parserState, $commentsBeforeRule);
} catch (UnexpectedTokenException $e) {
try {
$consumedText = $parserState->consumeUntil(["\n", ';', '}'], true);
// We need to “unfind” the matches to the end of the ruleSet as this will be matched later
if ($parserState->streql(\substr($consumedText, -1), '}')) {
$parserState->backtrack(1);
} else {
while ($parserState->comes(';')) {
$parserState->consume(';');
}
}
} catch (UnexpectedTokenException $e) {
// We’ve reached the end of the document. Just close the RuleSet.
return;
}
}
} else {
$declaration = Declaration::parse($parserState, $commentsBeforeRule);
}
if ($declaration instanceof Declaration) {
$ruleSet->addRule($declaration);
}
}
$parserState->consume('}');
}
/**
* @throws \UnexpectedValueException
* if the last `Declaration` is needed as a basis for setting position, but does not have a valid position,
* which should never happen
*/
public function addRule(Declaration $declarationToAdd, ?Declaration $sibling = null): void
{
$propertyName = $declarationToAdd->getPropertyName();
if (!isset($this->declarations[$propertyName])) {
$this->declarations[$propertyName] = [];
}
$position = \count($this->declarations[$propertyName]);
if ($sibling !== null) {
$siblingIsInSet = false;
$siblingPosition = \array_search($sibling, $this->declarations[$propertyName], true);
if ($siblingPosition !== false) {
$siblingIsInSet = true;
$position = $siblingPosition;
} else {
$siblingIsInSet = $this->hasRule($sibling);
if ($siblingIsInSet) {
// Maintain ordering within `$this->declarations[$propertyName]`
// by inserting before first `Declaration` with a same-or-later position than the sibling.
foreach ($this->declarations[$propertyName] as $index => $declaration) {
if (self::comparePositionable($declaration, $sibling) >= 0) {
$position = $index;
break;
}
}
}
}
if ($siblingIsInSet) {
// Increment column number of all existing rules on same line, starting at sibling
$siblingLineNumber = $sibling->getLineNumber();
$siblingColumnNumber = $sibling->getColumnNumber();
foreach ($this->declarations as $declarationsForAProperty) {
foreach ($declarationsForAProperty as $declaration) {
if (
$declaration->getLineNumber() === $siblingLineNumber &&
$declaration->getColumnNumber() >= $siblingColumnNumber
) {
$declaration->setPosition($siblingLineNumber, $declaration->getColumnNumber() + 1);
}
}
}
$declarationToAdd->setPosition($siblingLineNumber, $siblingColumnNumber);
}
}
if ($declarationToAdd->getLineNumber() === null) {
//this node is added manually, give it the next best line
$columnNumber = $declarationToAdd->getColumnNumber() ?? 0;
$declarations = $this->getRules();
$declarationsCount = \count($declarations);
if ($declarationsCount > 0) {
$last = $declarations[$declarationsCount - 1];
$lastsLineNumber = $last->getLineNumber();
if (!\is_int($lastsLineNumber)) {
throw new \UnexpectedValueException(
'A Declaration without a line number was found during addRule',
1750718399
);
}
$declarationToAdd->setPosition($lastsLineNumber + 1, $columnNumber);
} else {
$declarationToAdd->setPosition(1, $columnNumber);
}
} elseif ($declarationToAdd->getColumnNumber() === null) {
$declarationToAdd->setPosition($declarationToAdd->getLineNumber(), 0);
}
\array_splice($this->declarations[$propertyName], $position, 0, [$declarationToAdd]);
}
/**
* Returns all rules matching the given rule name
*
* @example $ruleSet->getRules('font') // returns array(0 => $declaration, …) or array().
*
* @example $ruleSet->getRules('font-')
* //returns an array of all rules either beginning with font- or matching font.
*
* @param string|null $searchPattern
* Pattern to search for. If null, returns all rules.
* If the pattern ends with a dash, all rules starting with the pattern are returned
* as well as one matching the pattern with the dash excluded.
*
* @return array<int<0, max>, Declaration>
*/
public function getRules(?string $searchPattern = null): array
{
$result = [];
foreach ($this->declarations as $propertyName => $declarations) {
// Either no search rule is given or the search rule matches the found rule exactly
// or the search rule ends in “-” and the found rule starts with the search rule.
if (
$searchPattern === null || $propertyName === $searchPattern
|| (
\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
&& (\strpos($propertyName, $searchPattern) === 0
|| $propertyName === \substr($searchPattern, 0, -1))
)
) {
$result = \array_merge($result, $declarations);
}
}
\usort($result, [self::class, 'comparePositionable']);
return $result;
}
/**
* Overrides all the rules of this set.
*
* @param array<Declaration> $declarations The rules to override with.
*/
public function setRules(array $declarations): void
{
$this->declarations = [];
foreach ($declarations as $declaration) {
$this->addRule($declaration);
}
}
/**
* Returns all rules matching the given pattern and returns them in an associative array with the rule’s name
* as keys. This method exists mainly for backwards-compatibility and is really only partially useful.
*
* Note: This method loses some information: Calling this (with an argument of `background-`) on a declaration block
* like `{ background-color: green; background-color; rgba(0, 127, 0, 0.7); }` will only yield an associative array
* containing the rgba-valued rule while `getRules()` would yield an indexed array containing both.
*
* @param string|null $searchPattern
* Pattern to search for. If null, returns all rules. If the pattern ends with a dash,
* all rules starting with the pattern are returned as well as one matching the pattern with the dash
* excluded.
*
* @return array<string, Declaration>
*/
public function getRulesAssoc(?string $searchPattern = null): array
{
/** @var array<string, Declaration> $result */
$result = [];
foreach ($this->getRules($searchPattern) as $declaration) {
$result[$declaration->getPropertyName()] = $declaration;
}
return $result;
}
/**
* Removes a `Declaration` from this `RuleSet` by identity.
*/
public function removeRule(Declaration $declarationToRemove): void
{
$nameOfPropertyToRemove = $declarationToRemove->getPropertyName();
if (!isset($this->declarations[$nameOfPropertyToRemove])) {
return;
}
foreach ($this->declarations[$nameOfPropertyToRemove] as $key => $declaration) {
if ($declaration === $declarationToRemove) {
unset($this->declarations[$nameOfPropertyToRemove][$key]);
}
}
}
/**
* Removes rules by property name or search pattern.
*
* @param string $searchPattern
* pattern to remove.
* If the pattern ends in a dash,
* all rules starting with the pattern are removed as well as one matching the pattern with the dash
* excluded.
*/
public function removeMatchingRules(string $searchPattern): void
{
foreach ($this->declarations as $propertyName => $declarations) {
// Either the search rule matches the found rule exactly
// or the search rule ends in “-” and the found rule starts with the search rule or equals it
// (without the trailing dash).
if (
$propertyName === $searchPattern
|| (\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
&& (\strpos($propertyName, $searchPattern) === 0
|| $propertyName === \substr($searchPattern, 0, -1)))
) {
unset($this->declarations[$propertyName]);
}
}
}
public function removeAllRules(): void
{
$this->declarations = [];
}
/**
* @internal
*/
public function render(OutputFormat $outputFormat): string
{
return $this->renderRules($outputFormat);
}
protected function renderRules(OutputFormat $outputFormat): string
{
$result = '';
$isFirst = true;
$nextLevelFormat = $outputFormat->nextLevel();
foreach ($this->getRules() as $declaration) {
$nextLevelFormatter = $nextLevelFormat->getFormatter();
$renderedRule = $nextLevelFormatter->safely(
static function () use ($declaration, $nextLevelFormat): string {
return $declaration->render($nextLevelFormat);
}
);
if ($renderedRule === null) {
continue;
}
if ($isFirst) {
$isFirst = false;
$result .= $nextLevelFormatter->spaceBeforeRules();
} else {
$result .= $nextLevelFormatter->spaceBetweenRules();
}
$result .= $renderedRule;
}
$formatter = $outputFormat->getFormatter();
if (!$isFirst) {
// Had some output
$result .= $formatter->spaceAfterRules();
}
return $formatter->removeLastSemicolon($result);
}
/**
* @return array<string, bool|int|float|string|array<mixed>|null>
*
* @internal
*/
public function getArrayRepresentation(): array
{
throw new \BadMethodCallException('`getArrayRepresentation` is not yet implemented for `' . self::class . '`');
}
/**
* @return int negative if `$first` is before `$second`; zero if they have the same position; positive otherwise
*
* @throws \UnexpectedValueException if either argument does not have a valid position, which should never happen
*/
private static function comparePositionable(Positionable $first, Positionable $second): int
{
$firstsLineNumber = $first->getLineNumber();
$secondsLineNumber = $second->getLineNumber();
if (!\is_int($firstsLineNumber) || !\is_int($secondsLineNumber)) {
throw new \UnexpectedValueException(
'A Declaration without a line number was passed to comparePositionable',
1750637683
);
}
if ($firstsLineNumber === $secondsLineNumber) {
$firstsColumnNumber = $first->getColumnNumber();
$secondsColumnNumber = $second->getColumnNumber();
if (!\is_int($firstsColumnNumber) || !\is_int($secondsColumnNumber)) {
throw new \UnexpectedValueException(
'A Declaration without a column number was passed to comparePositionable',
1750637761
);
}
return $firstsColumnNumber - $secondsColumnNumber;
}
return $firstsLineNumber - $secondsLineNumber;
}
private function hasRule(Declaration $declaration): bool
{
foreach ($this->declarations as $declarationsForAProperty) {
if (\in_array($declaration, $declarationsForAProperty, true)) {
return true;
}
}
return false;
}
}