Debian Codegraph @

vendor/sabberworm/php-css-parser/src/Property/Selector/Combinator.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Sabberworm\CSS\Property\Selector;
6
7 use Sabberworm\CSS\Comment\Comment;
8 use Sabberworm\CSS\OutputFormat;
9 use Sabberworm\CSS\Parsing\ParserState;
10 use Sabberworm\CSS\Parsing\UnexpectedTokenException;
11 use Sabberworm\CSS\ShortClassNameProvider;
12
13 /**
14 * Class representing a CSS selector combinator (space, `>`, `+`, or `~`).
15 *
16 * @phpstan-type ValidCombinatorValue ' '|'>'|'+'|'~'
17 */
18 class Combinator implements Component
19 {
20 use ShortClassNameProvider;
21
22 /**
23 * @var ValidCombinatorValue
24 */
25 private $value;
26
27 /**
28 * @param ValidCombinatorValue $value
29 */
30 public function __construct(string $value)
31 {
32 $this->setValue($value);
33 }
34
35 /**
36 * @param list<Comment> $comments
37 *
38 * @throws UnexpectedTokenException
39 *
40 * @internal
41 */
42 public static function parse(ParserState $parserState, array &$comments = []): self
43 {
44 $consumedWhitespace = $parserState->consumeWhiteSpace($comments);
45
46 $nextToken = $parserState->peek();
47 if (\in_array($nextToken, ['>', '+', '~'], true)) {
48 $value = $nextToken;
49 $parserState->consume(1);
50 $parserState->consumeWhiteSpace($comments);
51 } elseif ($consumedWhitespace !== '') {
52 $value = ' ';
53 } else {
54 throw new UnexpectedTokenException(
55 'combinator',
56 $nextToken,
57 'literal',
58 $parserState->currentLine()
59 );
60 }
61
62 return new self($value);
63 }
64
65 /**
66 * @return ValidCombinatorValue
67 */
68 public function getValue(): string
69 {
70 return $this->value;
71 }
72
73 /**
74 * @param non-empty-string $value
75 *
76 * @throws \UnexpectedValueException if `$value` is not either space, '>', '+' or '~'
77 */
78 public function setValue(string $value): void
79 {
80 if (!\in_array($value, [' ', '>', '+', '~'], true)) {
81 throw new \UnexpectedValueException('`' . $value . '` is not a valid selector combinator.');
82 }
83
84 $this->value = $value;
85 }
86
87 /**
88 * @return int<0, max>
89 */
90 public function getSpecificity(): int
91 {
92 return 0;
93 }
94
95 public function render(OutputFormat $outputFormat): string
96 {
97 $spacing = $outputFormat->getSpaceAroundSelectorCombinator();
98 if ($this->value === ' ') {
99 $rendering = $spacing !== '' ? $spacing : ' ';
100 } else {
101 $rendering = $spacing . $this->value . $spacing;
102 }
103
104 return $rendering;
105 }
106
107 /**
108 * @return array<string, bool|int|float|string|array<mixed>|null>
109 *
110 * @internal
111 */
112 public function getArrayRepresentation(): array
113 {
114 return [
115 'class' => $this->getShortClassName(),
116 'value' => $this->value,
117 ];
118 }
119 }