Debian Codegraph @

vendor/sabberworm/php-css-parser/src/RuleSet/RuleSet.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Sabberworm\CSS\RuleSet;
6
7 use Sabberworm\CSS\Comment\CommentContainer;
8 use Sabberworm\CSS\CSSElement;
9 use Sabberworm\CSS\CSSList\CSSListItem;
10 use Sabberworm\CSS\OutputFormat;
11 use Sabberworm\CSS\Parsing\ParserState;
12 use Sabberworm\CSS\Parsing\UnexpectedEOFException;
13 use Sabberworm\CSS\Parsing\UnexpectedTokenException;
14 use Sabberworm\CSS\Position\Position;
15 use Sabberworm\CSS\Position\Positionable;
16 use Sabberworm\CSS\Property\Declaration;
17
18 /**
19 * This class is a container for individual `Declaration`s.
20 *
21 * The most common form of a rule set is one constrained by a selector, i.e., a `DeclarationBlock`.
22 * However, unknown `AtRule`s (like `@font-face`) are rule sets as well.
23 *
24 * If you want to manipulate a `RuleSet`,
25 * use the methods `addDeclaration()`, `getDeclarations()`, `removeDeclaration()`, `removeMatchingDeclarations()`, etc.
26 *
27 * Note that `CSSListItem` extends both `Commentable` and `Renderable`, so those interfaces must also be implemented.
28 */
29 class RuleSet implements CSSElement, CSSListItem, Positionable, DeclarationList
30 {
31 use CommentContainer;
32 use LegacyDeclarationListMethods;
33 use Position;
34
35 /**
36 * the declarations in this rule set, using the property name as the key,
37 * with potentially multiple declarations per property name.
38 *
39 * @var array<string, array<int<0, max>, Declaration>>
40 */
41 private $declarations = [];
42
43 /**
44 * @param int<1, max>|null $lineNumber
45 */
46 public function __construct(?int $lineNumber = null)
47 {
48 $this->setPosition($lineNumber);
49 }
50
51 /**
52 * @throws UnexpectedTokenException
53 * @throws UnexpectedEOFException
54 *
55 * @internal since V8.8.0
56 */
57 public static function parseRuleSet(ParserState $parserState, RuleSet $ruleSet): void
58 {
59 while ($parserState->comes(';')) {
60 $parserState->consume(';');
61 }
62 while (true) {
63 $commentsBeforeDeclaration = [];
64 $parserState->consumeWhiteSpace($commentsBeforeDeclaration);
65 if ($parserState->comes('}')) {
66 break;
67 }
68 $declaration = null;
69 if ($parserState->getSettings()->usesLenientParsing()) {
70 try {
71 $declaration = Declaration::parse($parserState, $commentsBeforeDeclaration);
72 } catch (UnexpectedTokenException $e) {
73 try {
74 $consumedText = $parserState->consumeUntil(["\n", ';', '}'], true);
75 // We need to “unfind” the matches to the end of the ruleSet as this will be matched later
76 if ($parserState->streql(\substr($consumedText, -1), '}')) {
77 $parserState->backtrack(1);
78 } else {
79 while ($parserState->comes(';')) {
80 $parserState->consume(';');
81 }
82 }
83 } catch (UnexpectedTokenException $e) {
84 // We’ve reached the end of the document. Just close the RuleSet.
85 return;
86 }
87 }
88 } else {
89 $declaration = Declaration::parse($parserState, $commentsBeforeDeclaration);
90 }
91 if ($declaration instanceof Declaration) {
92 $ruleSet->addDeclaration($declaration);
93 }
94 }
95 $parserState->consume('}');
96 }
97
98 /**
99 * @throws \UnexpectedValueException
100 * if the last `Declaration` is needed as a basis for setting position, but does not have a valid position,
101 * which should never happen
102 */
103 public function addDeclaration(Declaration $declarationToAdd, ?Declaration $sibling = null): void
104 {
105 $propertyName = $declarationToAdd->getPropertyName();
106 if (!isset($this->declarations[$propertyName])) {
107 $this->declarations[$propertyName] = [];
108 }
109
110 $position = \count($this->declarations[$propertyName]);
111
112 if ($sibling !== null) {
113 $siblingIsInSet = false;
114 $siblingPosition = \array_search($sibling, $this->declarations[$propertyName], true);
115 if ($siblingPosition !== false) {
116 $siblingIsInSet = true;
117 $position = $siblingPosition;
118 } else {
119 $siblingIsInSet = $this->hasDeclaration($sibling);
120 if ($siblingIsInSet) {
121 // Maintain ordering within `$this->declarations[$propertyName]`
122 // by inserting before first `Declaration` with a same-or-later position than the sibling.
123 foreach ($this->declarations[$propertyName] as $index => $declaration) {
124 if (self::comparePositionable($declaration, $sibling) >= 0) {
125 $position = $index;
126 break;
127 }
128 }
129 }
130 }
131 if ($siblingIsInSet) {
132 // Increment column number of all existing declarations on same line, starting at sibling
133 $siblingLineNumber = $sibling->getLineNumber();
134 $siblingColumnNumber = $sibling->getColumnNumber();
135 foreach ($this->declarations as $declarationsForAProperty) {
136 foreach ($declarationsForAProperty as $declaration) {
137 if (
138 $declaration->getLineNumber() === $siblingLineNumber &&
139 $declaration->getColumnNumber() >= $siblingColumnNumber
140 ) {
141 $declaration->setPosition($siblingLineNumber, $declaration->getColumnNumber() + 1);
142 }
143 }
144 }
145 $declarationToAdd->setPosition($siblingLineNumber, $siblingColumnNumber);
146 }
147 }
148
149 if ($declarationToAdd->getLineNumber() === null) {
150 //this node is added manually, give it the next best line
151 $columnNumber = $declarationToAdd->getColumnNumber() ?? 0;
152 $declarations = $this->getDeclarations();
153 $declarationsCount = \count($declarations);
154 if ($declarationsCount > 0) {
155 $last = $declarations[$declarationsCount - 1];
156 $lastsLineNumber = $last->getLineNumber();
157 if (!\is_int($lastsLineNumber)) {
158 throw new \UnexpectedValueException(
159 'A Declaration without a line number was found during addDeclaration',
160 1750718399
161 );
162 }
163 $declarationToAdd->setPosition($lastsLineNumber + 1, $columnNumber);
164 } else {
165 $declarationToAdd->setPosition(1, $columnNumber);
166 }
167 } elseif ($declarationToAdd->getColumnNumber() === null) {
168 $declarationToAdd->setPosition($declarationToAdd->getLineNumber(), 0);
169 }
170
171 \array_splice($this->declarations[$propertyName], $position, 0, [$declarationToAdd]);
172 }
173
174 /**
175 * Returns all declarations matching the given property name
176 *
177 * @example $ruleSet->getDeclarations('font') // returns array(0 => $declaration, …) or array().
178 *
179 * @example $ruleSet->getDeclarations('font-')
180 * //returns an array of all declarations either beginning with font- or matching font.
181 *
182 * @param string|null $searchPattern
183 * Pattern to search for. If null, returns all declarations.
184 * If the pattern ends with a dash, all declarations starting with the pattern are returned
185 * as well as one matching the pattern with the dash excluded.
186 *
187 * @return array<int<0, max>, Declaration>
188 */
189 public function getDeclarations(?string $searchPattern = null): array
190 {
191 $result = [];
192 foreach ($this->declarations as $propertyName => $declarations) {
193 // Either no search pattern was given
194 // or the search pattern matches the found declaration's property name exactly
195 // or the search pattern ends in “-”
196 // ... and the found declaration's property name starts with the search pattern
197 if (
198 $searchPattern === null || $propertyName === $searchPattern
199 || (
200 \strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
201 && (\strpos($propertyName, $searchPattern) === 0
202 || $propertyName === \substr($searchPattern, 0, -1))
203 )
204 ) {
205 $result = \array_merge($result, $declarations);
206 }
207 }
208 \usort($result, [self::class, 'comparePositionable']);
209
210 return $result;
211 }
212
213 /**
214 * Overrides all the declarations of this set.
215 *
216 * @param array<Declaration> $declarations
217 */
218 public function setDeclarations(array $declarations): void
219 {
220 $this->declarations = [];
221 foreach ($declarations as $declaration) {
222 $this->addDeclaration($declaration);
223 }
224 }
225
226 /**
227 * Returns all declarations with property names matching the given pattern and returns them in an associative array
228 * with the property names as keys.
229 * This method exists mainly for backwards-compatibility and is really only partially useful.
230 *
231 * Note: This method loses some information: Calling this (with an argument of `background-`) on a declaration block
232 * like `{ background-color: green; background-color; rgba(0, 127, 0, 0.7); }` will only yield an associative array
233 * containing the rgba-valued declaration while `getDeclarations()` would yield an indexed array containing both.
234 *
235 * @param string|null $searchPattern
236 * Pattern to search for. If null, returns all declarations. If the pattern ends with a dash,
237 * all declarations starting with the pattern are returned as well as one matching the pattern with the dash
238 * excluded.
239 *
240 * @return array<string, Declaration>
241 */
242 public function getDeclarationsAssociative(?string $searchPattern = null): array
243 {
244 /** @var array<string, Declaration> $result */
245 $result = [];
246 foreach ($this->getDeclarations($searchPattern) as $declaration) {
247 $result[$declaration->getPropertyName()] = $declaration;
248 }
249
250 return $result;
251 }
252
253 /**
254 * Removes a `Declaration` from this `RuleSet` by identity.
255 */
256 public function removeDeclaration(Declaration $declarationToRemove): void
257 {
258 $nameOfPropertyToRemove = $declarationToRemove->getPropertyName();
259 if (!isset($this->declarations[$nameOfPropertyToRemove])) {
260 return;
261 }
262 foreach ($this->declarations[$nameOfPropertyToRemove] as $key => $declaration) {
263 if ($declaration === $declarationToRemove) {
264 unset($this->declarations[$nameOfPropertyToRemove][$key]);
265 }
266 }
267 }
268
269 /**
270 * Removes declarations by property name or search pattern.
271 *
272 * @param string $searchPattern
273 * pattern to remove.
274 * If the pattern ends in a dash,
275 * all declarations starting with the pattern are removed as well as one matching the pattern with the dash
276 * excluded.
277 */
278 public function removeMatchingDeclarations(string $searchPattern): void
279 {
280 foreach ($this->declarations as $propertyName => $declarations) {
281 // Either the search pattern matches the found declaration's property name exactly
282 // or the search pattern ends in “-” and the found declaration's property name starts with the search
283 // pattern or equals it (without the trailing dash).
284 if (
285 $propertyName === $searchPattern
286 || (\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
287 && (\strpos($propertyName, $searchPattern) === 0
288 || $propertyName === \substr($searchPattern, 0, -1)))
289 ) {
290 unset($this->declarations[$propertyName]);
291 }
292 }
293 }
294
295 public function removeAllDeclarations(): void
296 {
297 $this->declarations = [];
298 }
299
300 /**
301 * @internal
302 */
303 public function render(OutputFormat $outputFormat): string
304 {
305 return $this->renderDeclarations($outputFormat);
306 }
307
308 protected function renderDeclarations(OutputFormat $outputFormat): string
309 {
310 $result = '';
311 $isFirst = true;
312 $nextLevelFormat = $outputFormat->nextLevel();
313 foreach ($this->getDeclarations() as $declaration) {
314 $nextLevelFormatter = $nextLevelFormat->getFormatter();
315 $renderedDeclaration = $nextLevelFormatter->safely(
316 static function () use ($declaration, $nextLevelFormat): string {
317 return $declaration->render($nextLevelFormat);
318 }
319 );
320 if ($renderedDeclaration === null) {
321 continue;
322 }
323 if ($isFirst) {
324 $isFirst = false;
325 $result .= $nextLevelFormatter->spaceBeforeRules();
326 } else {
327 $result .= $nextLevelFormatter->spaceBetweenRules();
328 }
329 $result .= $renderedDeclaration;
330 }
331
332 $formatter = $outputFormat->getFormatter();
333 if (!$isFirst) {
334 // Had some output
335 $result .= $formatter->spaceAfterRules();
336 }
337
338 return $formatter->removeLastSemicolon($result);
339 }
340
341 /**
342 * @return array<string, bool|int|float|string|array<mixed>|null>
343 *
344 * @internal
345 */
346 public function getArrayRepresentation(): array
347 {
348 throw new \BadMethodCallException('`getArrayRepresentation` is not yet implemented for `' . self::class . '`');
349 }
350
351 /**
352 * @return int negative if `$first` is before `$second`; zero if they have the same position; positive otherwise
353 *
354 * @throws \UnexpectedValueException if either argument does not have a valid position, which should never happen
355 */
356 private static function comparePositionable(Positionable $first, Positionable $second): int
357 {
358 $firstsLineNumber = $first->getLineNumber();
359 $secondsLineNumber = $second->getLineNumber();
360 if (!\is_int($firstsLineNumber) || !\is_int($secondsLineNumber)) {
361 throw new \UnexpectedValueException(
362 'A Declaration without a line number was passed to comparePositionable',
363 1750637683
364 );
365 }
366
367 if ($firstsLineNumber === $secondsLineNumber) {
368 $firstsColumnNumber = $first->getColumnNumber();
369 $secondsColumnNumber = $second->getColumnNumber();
370 if (!\is_int($firstsColumnNumber) || !\is_int($secondsColumnNumber)) {
371 throw new \UnexpectedValueException(
372 'A Declaration without a column number was passed to comparePositionable',
373 1750637761
374 );
375 }
376 return $firstsColumnNumber - $secondsColumnNumber;
377 }
378
379 return $firstsLineNumber - $secondsLineNumber;
380 }
381
382 private function hasDeclaration(Declaration $declaration): bool
383 {
384 foreach ($this->declarations as $declarationsForAProperty) {
385 if (\in_array($declaration, $declarationsForAProperty, true)) {
386 return true;
387 }
388 }
389
390 return false;
391 }
392 }