> */ public function document(Document $document, RenderContext $ctx): array { return $this->nodes($document->nodes, $ctx); } /** * @param list $nodes * @return list> */ private function nodes(array $nodes, RenderContext $ctx): array { $out = []; foreach ($nodes as $node) { if (! $node instanceof Text && ! $node instanceof Element && ! $node instanceof Call) { continue; // 构建期的辅助节点(如配不上对的批注边界)不输出 } $rendered = $this->node($node, $ctx); $last = array_key_last($out); // 相邻文本并成一个节点 if ($rendered['type'] === 'text' && $last !== null && $out[$last]['type'] === 'text') { $out[$last]['value'] .= $rendered['value']; continue; } $out[] = $rendered; } return $out; } /** * @return array */ private function node(Node $node, RenderContext $ctx): array { if ($node instanceof Text) { return ['type' => 'text', 'value' => $node->value]; } if ($node instanceof Element) { $element = ['type' => 'el', 'tag' => $node->tag]; if ($node->attrs !== []) { $element['attrs'] = $node->attrs; } $element['children'] = $this->nodes($node->children, $ctx); return $element; } /** @var Call $node */ $children = $node->template->children($node, $ctx); return [ 'type' => 'tpl', 'name' => $node->template->component($node, $ctx), 'props' => (object) $this->props($node->template->props($node, $ctx), $ctx), 'children' => $children === null ? [] : $this->document($children, $ctx), ]; } /** * props 里的 Document 展开成节点数组(递归到数组里)。 * * @param array $props * @return array */ private function props(array $props, RenderContext $ctx): array { foreach ($props as $key => $value) { if ($value instanceof Document) { $props[$key] = $this->document($value, $ctx); } elseif (is_array($value)) { $props[$key] = $this->props($value, $ctx); } } return $props; } }