Parser.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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/SimonSapin/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;
  27. public function __construct(Tokenizer $tokenizer = null)
  28. {
  29. $this->tokenizer = $tokenizer ?: new Tokenizer();
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function parse($source)
  35. {
  36. $reader = new Reader($source);
  37. $stream = $this->tokenizer->tokenize($reader);
  38. return $this->parseSelectorList($stream);
  39. }
  40. /**
  41. * Parses the arguments for ":nth-child()" and friends.
  42. *
  43. * @param Token[] $tokens
  44. *
  45. * @return array
  46. *
  47. * @throws SyntaxErrorException
  48. */
  49. public static function parseSeries(array $tokens)
  50. {
  51. foreach ($tokens as $token) {
  52. if ($token->isString()) {
  53. throw SyntaxErrorException::stringAsFunctionArgument();
  54. }
  55. }
  56. $joined = trim(implode('', array_map(function (Token $token) {
  57. return $token->getValue();
  58. }, $tokens)));
  59. $int = function ($string) {
  60. if (!is_numeric($string)) {
  61. throw SyntaxErrorException::stringAsFunctionArgument();
  62. }
  63. return (int) $string;
  64. };
  65. switch (true) {
  66. case 'odd' === $joined:
  67. return [2, 1];
  68. case 'even' === $joined:
  69. return [2, 0];
  70. case 'n' === $joined:
  71. return [1, 0];
  72. case false === strpos($joined, 'n'):
  73. return [0, $int($joined)];
  74. }
  75. $split = explode('n', $joined);
  76. $first = isset($split[0]) ? $split[0] : null;
  77. return [
  78. $first ? ('-' === $first || '+' === $first ? $int($first.'1') : $int($first)) : 1,
  79. isset($split[1]) && $split[1] ? $int($split[1]) : 0,
  80. ];
  81. }
  82. /**
  83. * Parses selector nodes.
  84. *
  85. * @return array
  86. */
  87. private function parseSelectorList(TokenStream $stream)
  88. {
  89. $stream->skipWhitespace();
  90. $selectors = [];
  91. while (true) {
  92. $selectors[] = $this->parserSelectorNode($stream);
  93. if ($stream->getPeek()->isDelimiter([','])) {
  94. $stream->getNext();
  95. $stream->skipWhitespace();
  96. } else {
  97. break;
  98. }
  99. }
  100. return $selectors;
  101. }
  102. /**
  103. * Parses next selector or combined node.
  104. *
  105. * @return Node\SelectorNode
  106. *
  107. * @throws SyntaxErrorException
  108. */
  109. private function parserSelectorNode(TokenStream $stream)
  110. {
  111. list($result, $pseudoElement) = $this->parseSimpleSelector($stream);
  112. while (true) {
  113. $stream->skipWhitespace();
  114. $peek = $stream->getPeek();
  115. if ($peek->isFileEnd() || $peek->isDelimiter([','])) {
  116. break;
  117. }
  118. if (null !== $pseudoElement) {
  119. throw SyntaxErrorException::pseudoElementFound($pseudoElement, 'not at the end of a selector');
  120. }
  121. if ($peek->isDelimiter(['+', '>', '~'])) {
  122. $combinator = $stream->getNext()->getValue();
  123. $stream->skipWhitespace();
  124. } else {
  125. $combinator = ' ';
  126. }
  127. list($nextSelector, $pseudoElement) = $this->parseSimpleSelector($stream);
  128. $result = new Node\CombinedSelectorNode($result, $combinator, $nextSelector);
  129. }
  130. return new Node\SelectorNode($result, $pseudoElement);
  131. }
  132. /**
  133. * Parses next simple node (hash, class, pseudo, negation).
  134. *
  135. * @param bool $insideNegation
  136. *
  137. * @return array
  138. *
  139. * @throws SyntaxErrorException
  140. */
  141. private function parseSimpleSelector(TokenStream $stream, $insideNegation = false)
  142. {
  143. $stream->skipWhitespace();
  144. $selectorStart = \count($stream->getUsed());
  145. $result = $this->parseElementNode($stream);
  146. $pseudoElement = null;
  147. while (true) {
  148. $peek = $stream->getPeek();
  149. if ($peek->isWhitespace()
  150. || $peek->isFileEnd()
  151. || $peek->isDelimiter([',', '+', '>', '~'])
  152. || ($insideNegation && $peek->isDelimiter([')']))
  153. ) {
  154. break;
  155. }
  156. if (null !== $pseudoElement) {
  157. throw SyntaxErrorException::pseudoElementFound($pseudoElement, 'not at the end of a selector');
  158. }
  159. if ($peek->isHash()) {
  160. $result = new Node\HashNode($result, $stream->getNext()->getValue());
  161. } elseif ($peek->isDelimiter(['.'])) {
  162. $stream->getNext();
  163. $result = new Node\ClassNode($result, $stream->getNextIdentifier());
  164. } elseif ($peek->isDelimiter(['['])) {
  165. $stream->getNext();
  166. $result = $this->parseAttributeNode($result, $stream);
  167. } elseif ($peek->isDelimiter([':'])) {
  168. $stream->getNext();
  169. if ($stream->getPeek()->isDelimiter([':'])) {
  170. $stream->getNext();
  171. $pseudoElement = $stream->getNextIdentifier();
  172. continue;
  173. }
  174. $identifier = $stream->getNextIdentifier();
  175. if (\in_array(strtolower($identifier), ['first-line', 'first-letter', 'before', 'after'])) {
  176. // Special case: CSS 2.1 pseudo-elements can have a single ':'.
  177. // Any new pseudo-element must have two.
  178. $pseudoElement = $identifier;
  179. continue;
  180. }
  181. if (!$stream->getPeek()->isDelimiter(['('])) {
  182. $result = new Node\PseudoNode($result, $identifier);
  183. continue;
  184. }
  185. $stream->getNext();
  186. $stream->skipWhitespace();
  187. if ('not' === strtolower($identifier)) {
  188. if ($insideNegation) {
  189. throw SyntaxErrorException::nestedNot();
  190. }
  191. list($argument, $argumentPseudoElement) = $this->parseSimpleSelector($stream, true);
  192. $next = $stream->getNext();
  193. if (null !== $argumentPseudoElement) {
  194. throw SyntaxErrorException::pseudoElementFound($argumentPseudoElement, 'inside ::not()');
  195. }
  196. if (!$next->isDelimiter([')'])) {
  197. throw SyntaxErrorException::unexpectedToken('")"', $next);
  198. }
  199. $result = new Node\NegationNode($result, $argument);
  200. } else {
  201. $arguments = [];
  202. $next = null;
  203. while (true) {
  204. $stream->skipWhitespace();
  205. $next = $stream->getNext();
  206. if ($next->isIdentifier()
  207. || $next->isString()
  208. || $next->isNumber()
  209. || $next->isDelimiter(['+', '-'])
  210. ) {
  211. $arguments[] = $next;
  212. } elseif ($next->isDelimiter([')'])) {
  213. break;
  214. } else {
  215. throw SyntaxErrorException::unexpectedToken('an argument', $next);
  216. }
  217. }
  218. if (empty($arguments)) {
  219. throw SyntaxErrorException::unexpectedToken('at least one argument', $next);
  220. }
  221. $result = new Node\FunctionNode($result, $identifier, $arguments);
  222. }
  223. } else {
  224. throw SyntaxErrorException::unexpectedToken('selector', $peek);
  225. }
  226. }
  227. if (\count($stream->getUsed()) === $selectorStart) {
  228. throw SyntaxErrorException::unexpectedToken('selector', $stream->getPeek());
  229. }
  230. return [$result, $pseudoElement];
  231. }
  232. /**
  233. * Parses next element node.
  234. *
  235. * @return Node\ElementNode
  236. */
  237. private function parseElementNode(TokenStream $stream)
  238. {
  239. $peek = $stream->getPeek();
  240. if ($peek->isIdentifier() || $peek->isDelimiter(['*'])) {
  241. if ($peek->isIdentifier()) {
  242. $namespace = $stream->getNext()->getValue();
  243. } else {
  244. $stream->getNext();
  245. $namespace = null;
  246. }
  247. if ($stream->getPeek()->isDelimiter(['|'])) {
  248. $stream->getNext();
  249. $element = $stream->getNextIdentifierOrStar();
  250. } else {
  251. $element = $namespace;
  252. $namespace = null;
  253. }
  254. } else {
  255. $element = $namespace = null;
  256. }
  257. return new Node\ElementNode($namespace, $element);
  258. }
  259. /**
  260. * Parses next attribute node.
  261. *
  262. * @return Node\AttributeNode
  263. *
  264. * @throws SyntaxErrorException
  265. */
  266. private function parseAttributeNode(Node\NodeInterface $selector, TokenStream $stream)
  267. {
  268. $stream->skipWhitespace();
  269. $attribute = $stream->getNextIdentifierOrStar();
  270. if (null === $attribute && !$stream->getPeek()->isDelimiter(['|'])) {
  271. throw SyntaxErrorException::unexpectedToken('"|"', $stream->getPeek());
  272. }
  273. if ($stream->getPeek()->isDelimiter(['|'])) {
  274. $stream->getNext();
  275. if ($stream->getPeek()->isDelimiter(['='])) {
  276. $namespace = null;
  277. $stream->getNext();
  278. $operator = '|=';
  279. } else {
  280. $namespace = $attribute;
  281. $attribute = $stream->getNextIdentifier();
  282. $operator = null;
  283. }
  284. } else {
  285. $namespace = $operator = null;
  286. }
  287. if (null === $operator) {
  288. $stream->skipWhitespace();
  289. $next = $stream->getNext();
  290. if ($next->isDelimiter([']'])) {
  291. return new Node\AttributeNode($selector, $namespace, $attribute, 'exists', null);
  292. } elseif ($next->isDelimiter(['='])) {
  293. $operator = '=';
  294. } elseif ($next->isDelimiter(['^', '$', '*', '~', '|', '!'])
  295. && $stream->getPeek()->isDelimiter(['='])
  296. ) {
  297. $operator = $next->getValue().'=';
  298. $stream->getNext();
  299. } else {
  300. throw SyntaxErrorException::unexpectedToken('operator', $next);
  301. }
  302. }
  303. $stream->skipWhitespace();
  304. $value = $stream->getNext();
  305. if ($value->isNumber()) {
  306. // if the value is a number, it's casted into a string
  307. $value = new Token(Token::TYPE_STRING, (string) $value->getValue(), $value->getPosition());
  308. }
  309. if (!($value->isIdentifier() || $value->isString())) {
  310. throw SyntaxErrorException::unexpectedToken('string or identifier', $value);
  311. }
  312. $stream->skipWhitespace();
  313. $next = $stream->getNext();
  314. if (!$next->isDelimiter([']'])) {
  315. throw SyntaxErrorException::unexpectedToken('"]"', $next);
  316. }
  317. return new Node\AttributeNode($selector, $namespace, $attribute, $operator, $value->getValue());
  318. }
  319. }