StringHandler.php 2.4 KB

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\Handler;
  11. use Symfony\Component\CssSelector\Exception\InternalErrorException;
  12. use Symfony\Component\CssSelector\Exception\SyntaxErrorException;
  13. use Symfony\Component\CssSelector\Parser\Reader;
  14. use Symfony\Component\CssSelector\Parser\Token;
  15. use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping;
  16. use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns;
  17. use Symfony\Component\CssSelector\Parser\TokenStream;
  18. /**
  19. * CSS selector comment handler.
  20. *
  21. * This component is a port of the Python cssselect library,
  22. * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
  23. *
  24. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  25. *
  26. * @internal
  27. */
  28. class StringHandler implements HandlerInterface
  29. {
  30. private TokenizerPatterns $patterns;
  31. private TokenizerEscaping $escaping;
  32. public function __construct(TokenizerPatterns $patterns, TokenizerEscaping $escaping)
  33. {
  34. $this->patterns = $patterns;
  35. $this->escaping = $escaping;
  36. }
  37. public function handle(Reader $reader, TokenStream $stream): bool
  38. {
  39. $quote = $reader->getSubstring(1);
  40. if (!\in_array($quote, ["'", '"'])) {
  41. return false;
  42. }
  43. $reader->moveForward(1);
  44. $match = $reader->findPattern($this->patterns->getQuotedStringPattern($quote));
  45. if (!$match) {
  46. throw new InternalErrorException(sprintf('Should have found at least an empty match at %d.', $reader->getPosition()));
  47. }
  48. // check unclosed strings
  49. if (\strlen($match[0]) === $reader->getRemainingLength()) {
  50. throw SyntaxErrorException::unclosedString($reader->getPosition() - 1);
  51. }
  52. // check quotes pairs validity
  53. if ($quote !== $reader->getSubstring(1, \strlen($match[0]))) {
  54. throw SyntaxErrorException::unclosedString($reader->getPosition() - 1);
  55. }
  56. $string = $this->escaping->escapeUnicodeAndNewLine($match[0]);
  57. $stream->push(new Token(Token::TYPE_STRING, $string, $reader->getPosition()));
  58. $reader->moveForward(\strlen($match[0]) + 1);
  59. return true;
  60. }
  61. }