JsonRenderer.php 1.0 KB

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