StringHandler.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. public function __construct(
  31. private TokenizerPatterns $patterns,
  32. private TokenizerEscaping $escaping,
  33. ) {
  34. }
  35. public function handle(Reader $reader, TokenStream $stream): bool
  36. {
  37. $quote = $reader->getSubstring(1);
  38. if (!\in_array($quote, ["'", '"'])) {
  39. return false;
  40. }
  41. $reader->moveForward(1);
  42. $match = $reader->findPattern($this->patterns->getQuotedStringPattern($quote));
  43. if (!$match) {
  44. throw new InternalErrorException(\sprintf('Should have found at least an empty match at %d.', $reader->getPosition()));
  45. }
  46. // check unclosed strings
  47. if (\strlen($match[0]) === $reader->getRemainingLength()) {
  48. throw SyntaxErrorException::unclosedString($reader->getPosition() - 1);
  49. }
  50. // check quotes pairs validity
  51. if ($quote !== $reader->getSubstring(1, \strlen($match[0]))) {
  52. throw SyntaxErrorException::unclosedString($reader->getPosition() - 1);
  53. }
  54. $string = $this->escaping->escapeUnicodeAndNewLine($match[0]);
  55. $stream->push(new Token(Token::TYPE_STRING, $string, $reader->getPosition()));
  56. $reader->moveForward(\strlen($match[0]) + 1);
  57. return true;
  58. }
  59. }