HtmlFragment.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. <?php
  2. namespace App\Services\Markup\Html;
  3. use App\Services\Markup\Ir\Element;
  4. use App\Services\Markup\Ir\Node;
  5. use App\Services\Markup\Ir\Text;
  6. use Closure;
  7. use DOMDocument;
  8. use DOMElement;
  9. use DOMNode;
  10. use DOMText;
  11. /**
  12. * 原始 HTML → IR 节点(过 {@see HtmlPolicy})。
  13. *
  14. * 两种来源:
  15. * - HTML 块(CommonMark 的 HtmlBlock):整块交给 DOMDocument 解析
  16. * - 行内 HTML(HtmlInline):CommonMark 把 `<u>a</u>` 拆成「开标签、文字、闭标签」三个兄弟节点,
  17. * 由 {@see InlineHtmlAssembler} 按栈重新配对
  18. */
  19. final class HtmlFragment
  20. {
  21. /**
  22. * @param Closure(string): list<Node> $expandText 文字 → 节点(展开其中的模板占位符)
  23. * @return list<Node>
  24. */
  25. public static function parseBlock(string $html, Closure $expandText): array
  26. {
  27. $doc = new DOMDocument;
  28. $previous = libxml_use_internal_errors(true);
  29. $doc->loadHTML(
  30. '<?xml encoding="UTF-8"><div>'.$html.'</div>',
  31. LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOERROR | LIBXML_NOWARNING,
  32. );
  33. libxml_clear_errors();
  34. libxml_use_internal_errors($previous);
  35. $root = null;
  36. foreach ($doc->childNodes as $child) {
  37. if ($child instanceof DOMElement) {
  38. $root = $child;
  39. break;
  40. }
  41. }
  42. return $root === null ? [] : self::children($root, $expandText);
  43. }
  44. /**
  45. * @param Closure(string): list<Node> $expandText
  46. * @return list<Node>
  47. */
  48. private static function children(DOMNode $parent, Closure $expandText): array
  49. {
  50. $nodes = [];
  51. foreach ($parent->childNodes as $child) {
  52. if ($child instanceof DOMText) {
  53. array_push($nodes, ...$expandText($child->data));
  54. } elseif ($child instanceof DOMElement) {
  55. $element = self::element($child->tagName, self::domAttrs($child));
  56. if ($element === false) {
  57. continue;
  58. }
  59. $element->children = self::children($child, $expandText);
  60. $nodes[] = $element;
  61. }
  62. }
  63. return $nodes;
  64. }
  65. /**
  66. * 按白名单建元素;false 表示连同内容丢掉。
  67. *
  68. * @param array<string, string> $attrs
  69. */
  70. public static function element(string $tag, array $attrs): Element|false
  71. {
  72. $tag = strtolower($tag);
  73. $decision = HtmlPolicy::tag($tag);
  74. if ($decision === false) {
  75. return false;
  76. }
  77. if ($decision === null) {
  78. return new Element('span', ['data-tag' => $tag] + HtmlPolicy::attrs('span', $attrs));
  79. }
  80. return new Element($decision, HtmlPolicy::attrs($decision, $attrs));
  81. }
  82. /**
  83. * @return array<string, string>
  84. */
  85. private static function domAttrs(DOMElement $element): array
  86. {
  87. $attrs = [];
  88. foreach ($element->attributes as $attr) {
  89. $attrs[strtolower($attr->nodeName)] = $attr->nodeValue ?? '';
  90. }
  91. return $attrs;
  92. }
  93. /**
  94. * 解析一个标签字面量。
  95. *
  96. * @return array{kind: 'open'|'close'|'other', tag: string, attrs: array<string, string>, selfClosing: bool}
  97. */
  98. public static function tagLiteral(string $literal): array
  99. {
  100. if (preg_match('/^<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>$/', $literal, $m) === 1) {
  101. return ['kind' => 'close', 'tag' => strtolower($m[1]), 'attrs' => [], 'selfClosing' => false];
  102. }
  103. if (preg_match('/^<([a-zA-Z][a-zA-Z0-9-]*)(.*?)(\/?)>$/s', $literal, $m) !== 1) {
  104. return ['kind' => 'other', 'tag' => '', 'attrs' => [], 'selfClosing' => false];
  105. }
  106. $attrs = [];
  107. preg_match_all(
  108. '/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'=<>`]+)))?/',
  109. $m[2],
  110. $pairs,
  111. PREG_SET_ORDER,
  112. );
  113. foreach ($pairs as $pair) {
  114. $value = ($pair[2] ?? '') !== '' ? $pair[2] : ((($pair[3] ?? '') !== '') ? $pair[3] : ($pair[4] ?? ''));
  115. $attrs[strtolower($pair[1])] = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  116. }
  117. return ['kind' => 'open', 'tag' => strtolower($m[1]), 'attrs' => $attrs, 'selfClosing' => $m[3] === '/'];
  118. }
  119. public static function text(string $value): Text
  120. {
  121. return new Text($value);
  122. }
  123. }