Parser.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\CssSelector\Parser;
  11. use Symfony\Component\CssSelector\Exception\SyntaxErrorException;
  12. use Symfony\Component\CssSelector\Node;
  13. use Symfony\Component\CssSelector\Parser\Tokenizer\Tokenizer;
  14. /**
  15. * CSS selector parser.
  16. *
  17. * This component is a port of the Python cssselect library,
  18. * which is copyright Ian Bicking, @see https://github.com/scrapy/cssselect.
  19. *
  20. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  21. *
  22. * @internal
  23. */
  24. class Parser implements ParserInterface
  25. {
  26. private Tokenizer $tokenizer;
  27. public function __construct(Tokenizer $tokenizer = null)
  28. {
  29. $this->tokenizer = $tokenizer ?? new Tokenizer();
  30. }
  31. public function parse(string $source): array
  32. {
  33. $reader = new Reader($source);
  34. $stream = $this->tokenizer->tokenize($reader);
  35. return $this->parseSelectorList($stream);
  36. }
  37. /**
  38. * Parses the arguments for ":nth-child()" and friends.
  39. *
  40. * @param Token[] $tokens
  41. *
  42. * @throws SyntaxErrorException
  43. */
  44. public static function parseSeries(array $tokens): array
  45. {
  46. foreach ($tokens as $token) {
  47. if ($token->isString()) {
  48. throw SyntaxErrorException::stringAsFunctionArgument();
  49. }
  50. }
  51. $joined = trim(implode('', array_map(fn (Token $token) => $token->getValue(), $tokens)));
  52. $int = function ($string) {
  53. if (!is_numeric($string)) {
  54. throw SyntaxErrorException::stringAsFunctionArgument();
  55. }
  56. return (int) $string;
  57. };
  58. switch (true) {
  59. case 'odd' === $joined:
  60. return [2, 1];
  61. case 'even' === $joined:
  62. return [2, 0];
  63. case 'n' === $joined:
  64. return [1, 0];
  65. case !str_contains($joined, 'n'):
  66. return [0, $int($joined)];
  67. }
  68. $split = explode('n', $joined);
  69. $first = $split[0] ?? null;
  70. return [
  71. $first ? ('-' === $first || '+' === $first ? $int($first.'1') : $int($first)) : 1,
  72. isset($split[1]) && $split[1] ? $int($split[1]) : 0,
  73. ];
  74. }
  75. private function parseSelectorList(TokenStream $stream): array
  76. {
  77. $stream->skipWhitespace();
  78. $selectors = [];
  79. while (true) {
  80. $selectors[] = $this->parserSelectorNode($stream);
  81. if ($stream->getPeek()->isDelimiter([','])) {
  82. $stream->getNext();
  83. $stream->skipWhitespace();
  84. } else {
  85. break;
  86. }
  87. }
  88. return $selectors;
  89. }
  90. private function parserSelectorNode(TokenStream $stream): Node\SelectorNode
  91. {
  92. [$result, $pseudoElement] = $this->parseSimpleSelector($stream);
  93. while (true) {
  94. $stream->skipWhitespace();
  95. $peek = $stream->getPeek();
  96. if ($peek->isFileEnd() || $peek->isDelimiter([','])) {
  97. break;
  98. }
  99. if (null !== $pseudoElement) {
  100. throw SyntaxErrorException::pseudoElementFound($pseudoElement, 'not at the end of a selector');
  101. }
  102. if ($peek->isDelimiter(['+', '>', '~'])) {
  103. $combinator = $stream->getNext()->getValue();
  104. $stream->skipWhitespace();
  105. } else {
  106. $combinator = ' ';
  107. }
  108. [$nextSelector, $pseudoElement] = $this->parseSimpleSelector($stream);
  109. $result = new Node\CombinedSelectorNode($result, $combinator, $nextSelector);
  110. }
  111. return new Node\SelectorNode($result, $pseudoElement);
  112. }
  113. /**
  114. * Parses next simple node (hash, class, pseudo, negation).
  115. *
  116. * @throws SyntaxErrorException
  117. */
  118. private function parseSimpleSelector(TokenStream $stream, bool $insideNegation = false): array
  119. {
  120. $stream->skipWhitespace();
  121. $selectorStart = \count($stream->getUsed());
  122. $result = $this->parseElementNode($stream);
  123. $pseudoElement = null;
  124. while (true) {
  125. $peek = $stream->getPeek();
  126. if ($peek->isWhitespace()
  127. || $peek->isFileEnd()
  128. || $peek->isDelimiter([',', '+', '>', '~'])
  129. || ($insideNegation && $peek->isDelimiter([')']))
  130. ) {
  131. break;
  132. }
  133. if (null !== $pseudoElement) {
  134. throw SyntaxErrorException::pseudoElementFound($pseudoElement, 'not at the end of a selector');
  135. }
  136. if ($peek->isHash()) {
  137. $result = new Node\HashNode($result, $stream->getNext()->getValue());
  138. } elseif ($peek->isDelimiter(['.'])) {
  139. $stream->getNext();
  140. $result = new Node\ClassNode($result, $stream->getNextIdentifier());
  141. } elseif ($peek->isDelimiter(['['])) {
  142. $stream->getNext();
  143. $result = $this->parseAttributeNode($result, $stream);
  144. } elseif ($peek->isDelimiter([':'])) {
  145. $stream->getNext();
  146. if ($stream->getPeek()->isDelimiter([':'])) {
  147. $stream->getNext();
  148. $pseudoElement = $stream->getNextIdentifier();
  149. continue;
  150. }
  151. $identifier = $stream->getNextIdentifier();
  152. if (\in_array(strtolower($identifier), ['first-line', 'first-letter', 'before', 'after'])) {
  153. // Special case: CSS 2.1 pseudo-elements can have a single ':'.
  154. // Any new pseudo-element must have two.
  155. $pseudoElement = $identifier;
  156. continue;
  157. }
  158. if (!$stream->getPeek()->isDelimiter(['('])) {
  159. $result = new Node\PseudoNode($result, $identifier);
  160. if ('Pseudo[Element[*]:scope]' === $result->__toString()) {
  161. $used = \count($stream->getUsed());
  162. if (!(2 === $used
  163. || 3 === $used && $stream->getUsed()[0]->isWhiteSpace()
  164. || $used >= 3 && $stream->getUsed()[$used - 3]->isDelimiter([','])
  165. || $used >= 4
  166. && $stream->getUsed()[$used - 3]->isWhiteSpace()
  167. && $stream->getUsed()[$used - 4]->isDelimiter([','])
  168. )) {
  169. throw SyntaxErrorException::notAtTheStartOfASelector('scope');
  170. }
  171. }
  172. continue;
  173. }
  174. $stream->getNext();
  175. $stream->skipWhitespace();
  176. if ('not' === strtolower($identifier)) {
  177. if ($insideNegation) {
  178. throw SyntaxErrorException::nestedNot();
  179. }
  180. [$argument, $argumentPseudoElement] = $this->parseSimpleSelector($stream, true);
  181. $next = $stream->getNext();
  182. if (null !== $argumentPseudoElement) {
  183. throw SyntaxErrorException::pseudoElementFound($argumentPseudoElement, 'inside ::not()');
  184. }
  185. if (!$next->isDelimiter([')'])) {
  186. throw SyntaxErrorException::unexpectedToken('")"', $next);
  187. }
  188. $result = new Node\NegationNode($result, $argument);
  189. } else {
  190. $arguments = [];
  191. $next = null;
  192. while (true) {
  193. $stream->skipWhitespace();
  194. $next = $stream->getNext();
  195. if ($next->isIdentifier()
  196. || $next->isString()
  197. || $next->isNumber()
  198. || $next->isDelimiter(['+', '-'])
  199. ) {
  200. $arguments[] = $next;
  201. } elseif ($next->isDelimiter([')'])) {
  202. break;
  203. } else {
  204. throw SyntaxErrorException::unexpectedToken('an argument', $next);
  205. }
  206. }
  207. if (!$arguments) {
  208. throw SyntaxErrorException::unexpectedToken('at least one argument', $next);
  209. }
  210. $result = new Node\FunctionNode($result, $identifier, $arguments);
  211. }
  212. } else {
  213. throw SyntaxErrorException::unexpectedToken('selector', $peek);
  214. }
  215. }
  216. if (\count($stream->getUsed()) === $selectorStart) {
  217. throw SyntaxErrorException::unexpectedToken('selector', $stream->getPeek());
  218. }
  219. return [$result, $pseudoElement];
  220. }
  221. private function parseElementNode(TokenStream $stream): Node\ElementNode
  222. {
  223. $peek = $stream->getPeek();
  224. if ($peek->isIdentifier() || $peek->isDelimiter(['*'])) {
  225. if ($peek->isIdentifier()) {
  226. $namespace = $stream->getNext()->getValue();
  227. } else {
  228. $stream->getNext();
  229. $namespace = null;
  230. }
  231. if ($stream->getPeek()->isDelimiter(['|'])) {
  232. $stream->getNext();
  233. $element = $stream->getNextIdentifierOrStar();
  234. } else {
  235. $element = $namespace;
  236. $namespace = null;
  237. }
  238. } else {
  239. $element = $namespace = null;
  240. }
  241. return new Node\ElementNode($namespace, $element);
  242. }
  243. private function parseAttributeNode(Node\NodeInterface $selector, TokenStream $stream): Node\AttributeNode
  244. {
  245. $stream->skipWhitespace();
  246. $attribute = $stream->getNextIdentifierOrStar();
  247. if (null === $attribute && !$stream->getPeek()->isDelimiter(['|'])) {
  248. throw SyntaxErrorException::unexpectedToken('"|"', $stream->getPeek());
  249. }
  250. if ($stream->getPeek()->isDelimiter(['|'])) {
  251. $stream->getNext();
  252. if ($stream->getPeek()->isDelimiter(['='])) {
  253. $namespace = null;
  254. $stream->getNext();
  255. $operator = '|=';
  256. } else {
  257. $namespace = $attribute;
  258. $attribute = $stream->getNextIdentifier();
  259. $operator = null;
  260. }
  261. } else {
  262. $namespace = $operator = null;
  263. }
  264. if (null === $operator) {
  265. $stream->skipWhitespace();
  266. $next = $stream->getNext();
  267. if ($next->isDelimiter([']'])) {
  268. return new Node\AttributeNode($selector, $namespace, $attribute, 'exists', null);
  269. } elseif ($next->isDelimiter(['='])) {
  270. $operator = '=';
  271. } elseif ($next->isDelimiter(['^', '$', '*', '~', '|', '!'])
  272. && $stream->getPeek()->isDelimiter(['='])
  273. ) {
  274. $operator = $next->getValue().'=';
  275. $stream->getNext();
  276. } else {
  277. throw SyntaxErrorException::unexpectedToken('operator', $next);
  278. }
  279. }
  280. $stream->skipWhitespace();
  281. $value = $stream->getNext();
  282. if ($value->isNumber()) {
  283. // if the value is a number, it's casted into a string
  284. $value = new Token(Token::TYPE_STRING, (string) $value->getValue(), $value->getPosition());
  285. }
  286. if (!($value->isIdentifier() || $value->isString())) {
  287. throw SyntaxErrorException::unexpectedToken('string or identifier', $value);
  288. }
  289. $stream->skipWhitespace();
  290. $next = $stream->getNext();
  291. if (!$next->isDelimiter([']'])) {
  292. throw SyntaxErrorException::unexpectedToken('"]"', $next);
  293. }
  294. return new Node\AttributeNode($selector, $namespace, $attribute, $operator, $value->getValue());
  295. }
  296. }