No Description

Tokenizer.php 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\Tokenizer;
  11. use Symfony\Component\CssSelector\Parser\Handler;
  12. use Symfony\Component\CssSelector\Parser\Reader;
  13. use Symfony\Component\CssSelector\Parser\Token;
  14. use Symfony\Component\CssSelector\Parser\TokenStream;
  15. /**
  16. * CSS selector tokenizer.
  17. *
  18. * This component is a port of the Python cssselect library,
  19. * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
  20. *
  21. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  22. *
  23. * @internal
  24. */
  25. class Tokenizer
  26. {
  27. /**
  28. * @var Handler\HandlerInterface[]
  29. */
  30. private $handlers;
  31. public function __construct()
  32. {
  33. $patterns = new TokenizerPatterns();
  34. $escaping = new TokenizerEscaping($patterns);
  35. $this->handlers = [
  36. new Handler\WhitespaceHandler(),
  37. new Handler\IdentifierHandler($patterns, $escaping),
  38. new Handler\HashHandler($patterns, $escaping),
  39. new Handler\StringHandler($patterns, $escaping),
  40. new Handler\NumberHandler($patterns),
  41. new Handler\CommentHandler(),
  42. ];
  43. }
  44. /**
  45. * Tokenize selector source code.
  46. */
  47. public function tokenize(Reader $reader): TokenStream
  48. {
  49. $stream = new TokenStream();
  50. while (!$reader->isEOF()) {
  51. foreach ($this->handlers as $handler) {
  52. if ($handler->handle($reader, $stream)) {
  53. continue 2;
  54. }
  55. }
  56. $stream->push(new Token(Token::TYPE_DELIMITER, $reader->getSubstring(1), $reader->getPosition()));
  57. $reader->moveForward(1);
  58. }
  59. return $stream
  60. ->push(new Token(Token::TYPE_FILE_END, null, $reader->getPosition()))
  61. ->freeze();
  62. }
  63. }