StringHandler.php 2.4 KB

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