菜谱项目

TokenizerEscaping.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  29. * @param string $value
  30. *
  31. * @return string
  32. */
  33. public function escapeUnicode($value)
  34. {
  35. $value = $this->replaceUnicodeSequences($value);
  36. return preg_replace($this->patterns->getSimpleEscapePattern(), '$1', $value);
  37. }
  38. /**
  39. * @param string $value
  40. *
  41. * @return string
  42. */
  43. public function escapeUnicodeAndNewLine($value)
  44. {
  45. $value = preg_replace($this->patterns->getNewLineEscapePattern(), '', $value);
  46. return $this->escapeUnicode($value);
  47. }
  48. /**
  49. * @param string $value
  50. *
  51. * @return string
  52. */
  53. private function replaceUnicodeSequences($value)
  54. {
  55. return preg_replace_callback($this->patterns->getUnicodeEscapePattern(), function ($match) {
  56. $c = hexdec($match[1]);
  57. if (0x80 > $c %= 0x200000) {
  58. return chr($c);
  59. }
  60. if (0x800 > $c) {
  61. return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
  62. }
  63. if (0x10000 > $c) {
  64. return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  65. }
  66. }, $value);
  67. }
  68. }