You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.4 KiB

3 years ago
  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 %d.', $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. }