JsonRenderer.php 974 B

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. namespace App\Services\Template\Renderers;
  3. use App\Services\Template\Contracts\RendererInterface;
  4. use App\Services\Template\ParsedDocument;
  5. use App\Services\Template\TemplateNode;
  6. use App\Services\Template\TextNode;
  7. // ================== JSON 渲染器 ==================
  8. class JsonRenderer implements RendererInterface
  9. {
  10. public function render(ParsedDocument $document): string
  11. {
  12. $data = [
  13. 'type' => $document->type,
  14. 'content' => array_map(fn ($node) => $node->toArray(), $document->content),
  15. 'meta' => $document->meta,
  16. ];
  17. return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  18. }
  19. public function renderTemplate(TemplateNode $template): string
  20. {
  21. return json_encode($template->toArray(), JSON_UNESCAPED_UNICODE);
  22. }
  23. public function renderText(TextNode $text): string
  24. {
  25. return json_encode($text->toArray(), JSON_UNESCAPED_UNICODE);
  26. }
  27. }