Placeholder.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Services\Markup\Parsing;
  3. /**
  4. * 预扫描用的占位符:私用区字符包住模板调用的下标,`\u{E000}12\u{E001}`。
  5. *
  6. * CommonMark 把它当普通文字,所以模板里的 `|`、空行、列表符号都不会打断段落或表格;
  7. * 解析完再由 {@see PlaceholderParser} 换回模板节点。
  8. */
  9. final class Placeholder
  10. {
  11. public const OPEN = "\u{E000}";
  12. public const CLOSE = "\u{E001}";
  13. public const PATTERN = '/'."\u{E000}".'(\d+)'."\u{E001}".'/u';
  14. public static function make(int $index): string
  15. {
  16. return self::OPEN.$index.self::CLOSE;
  17. }
  18. /**
  19. * 去掉源码里本来就有的占位符字符,免得与真占位符混淆。
  20. */
  21. public static function strip(string $source): string
  22. {
  23. return str_replace([self::OPEN, self::CLOSE], '', $source);
  24. }
  25. /**
  26. * 把文字里的占位符换回源码原文(代码块、原始 HTML 属性等不该展开模板的地方用)。
  27. *
  28. * @param array<int, string> $raws 下标 => 原文
  29. */
  30. public static function restore(string $text, array $raws): string
  31. {
  32. return (string) preg_replace_callback(
  33. self::PATTERN,
  34. fn (array $m) => $raws[(int) $m[1]] ?? '',
  35. $text,
  36. );
  37. }
  38. }