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.

65 lines
1.7 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\Tokenizer;
  11. /**
  12. * CSS selector tokenizer escaping applier.
  13. *
  14. * This component is a port of the Python cssselect library,
  15. * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
  16. *
  17. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  18. *
  19. * @internal
  20. */
  21. class TokenizerEscaping
  22. {
  23. private $patterns;
  24. public function __construct(TokenizerPatterns $patterns)
  25. {
  26. $this->patterns = $patterns;
  27. }
  28. public function escapeUnicode(string $value): string
  29. {
  30. $value = $this->replaceUnicodeSequences($value);
  31. return preg_replace($this->patterns->getSimpleEscapePattern(), '$1', $value);
  32. }
  33. public function escapeUnicodeAndNewLine(string $value): string
  34. {
  35. $value = preg_replace($this->patterns->getNewLineEscapePattern(), '', $value);
  36. return $this->escapeUnicode($value);
  37. }
  38. private function replaceUnicodeSequences(string $value): string
  39. {
  40. return preg_replace_callback($this->patterns->getUnicodeEscapePattern(), function ($match) {
  41. $c = hexdec($match[1]);
  42. if (0x80 > $c %= 0x200000) {
  43. return \chr($c);
  44. }
  45. if (0x800 > $c) {
  46. return \chr(0xC0 | $c >> 6).\chr(0x80 | $c & 0x3F);
  47. }
  48. if (0x10000 > $c) {
  49. return \chr(0xE0 | $c >> 12).\chr(0x80 | $c >> 6 & 0x3F).\chr(0x80 | $c & 0x3F);
  50. }
  51. return '';
  52. }, $value);
  53. }
  54. }