Tokenizer.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. * @return TokenStream
  48. */
  49. public function tokenize(Reader $reader)
  50. {
  51. $stream = new TokenStream();
  52. while (!$reader->isEOF()) {
  53. foreach ($this->handlers as $handler) {
  54. if ($handler->handle($reader, $stream)) {
  55. continue 2;
  56. }
  57. }
  58. $stream->push(new Token(Token::TYPE_DELIMITER, $reader->getSubstring(1), $reader->getPosition()));
  59. $reader->moveForward(1);
  60. }
  61. return $stream
  62. ->push(new Token(Token::TYPE_FILE_END, null, $reader->getPosition()))
  63. ->freeze();
  64. }
  65. }