InlineHtmlAssembler.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Services\Markup\Html;
  3. use App\Services\Markup\Ir\Element;
  4. use App\Services\Markup\Ir\Node;
  5. /**
  6. * 把行内节点序列里散落的 HTML 开 / 闭标签重新配成嵌套元素。
  7. *
  8. * 闭标签找栈里最近的同名元素,中间没闭合的一并闭合;找不到的闭标签忽略;到结尾仍未闭合的就地闭合。
  9. * 被 {@see HtmlPolicy} 丢掉的标签,直到它闭合为止的内容也一起丢掉。
  10. */
  11. final class InlineHtmlAssembler
  12. {
  13. /** @var list<Node> */
  14. private array $root = [];
  15. /** @var list<array{tag: string, element: Element|null}> element 为 null 表示被丢掉的标签 */
  16. private array $stack = [];
  17. public function add(Node $node): void
  18. {
  19. foreach ($this->stack as $frame) {
  20. if ($frame['element'] === null) {
  21. return;
  22. }
  23. }
  24. $top = end($this->stack);
  25. if ($top === false) {
  26. $this->root[] = $node;
  27. } else {
  28. $top['element']->children[] = $node;
  29. }
  30. }
  31. public function tag(string $literal): void
  32. {
  33. $tag = HtmlFragment::tagLiteral($literal);
  34. if ($tag['kind'] === 'close') {
  35. $this->close($tag['tag']);
  36. return;
  37. }
  38. if ($tag['kind'] !== 'open') {
  39. return;
  40. }
  41. $element = HtmlFragment::element($tag['tag'], $tag['attrs']);
  42. $void = $tag['selfClosing'] || in_array($tag['tag'], HtmlPolicy::VOID, true);
  43. if ($element === false) {
  44. if (! $void) {
  45. $this->stack[] = ['tag' => $tag['tag'], 'element' => null];
  46. }
  47. return;
  48. }
  49. $this->add($element);
  50. if (! $void) {
  51. $this->stack[] = ['tag' => $tag['tag'], 'element' => $element];
  52. }
  53. }
  54. private function close(string $tag): void
  55. {
  56. for ($i = count($this->stack) - 1; $i >= 0; $i--) {
  57. if ($this->stack[$i]['tag'] === $tag) {
  58. $this->stack = array_slice($this->stack, 0, $i);
  59. return;
  60. }
  61. }
  62. }
  63. /**
  64. * @return list<Node>
  65. */
  66. public function nodes(): array
  67. {
  68. return $this->root;
  69. }
  70. }