StringHandler.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. }