TplTemplate.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Services\Markup\Templates;
  3. use App\Services\Markup\Format;
  4. use App\Services\Markup\Ir\Call;
  5. use App\Services\Markup\Ir\Document;
  6. use App\Services\Markup\Render\RenderContext;
  7. use App\Services\Markup\Resolve\Resolver;
  8. use App\Services\Markup\Resolve\TplLoader;
  9. /**
  10. * 用户自定义模板:`{{Tpl:名字|a|b=c}}`。正文是标题为「Tpl:名字」的文章,参数经 Mustache 代入
  11. * (`{{1}}`、`{{b}}`),结果再按 markdown 渲染。
  12. */
  13. final class TplTemplate extends Template
  14. {
  15. protected string $component = 'tpl';
  16. protected function acceptsAnyName(): bool
  17. {
  18. return true;
  19. }
  20. public function collect(Call $call, Resolver $resolver): void
  21. {
  22. $call->data['tpl'] = $resolver->loader(TplLoader::class)->request($call->name, $call->params->all(), $call->scope);
  23. }
  24. /**
  25. * @return array{content: string, document: ?Document}|null
  26. */
  27. private function resolved(Call $call, RenderContext $ctx): ?array
  28. {
  29. return $ctx->loader(TplLoader::class)->result((string) ($call->data['tpl'] ?? ''));
  30. }
  31. /**
  32. * @return array<string, mixed>
  33. */
  34. public function props(Call $call, RenderContext $ctx): array
  35. {
  36. return ['name' => $call->name];
  37. }
  38. public function children(Call $call, RenderContext $ctx): ?Document
  39. {
  40. return $this->resolved($call, $ctx)['document'] ?? null;
  41. }
  42. private function rendered(Call $call, RenderContext $ctx): string
  43. {
  44. $resolved = $this->resolved($call, $ctx);
  45. if ($resolved === null) {
  46. return '';
  47. }
  48. return $resolved['document'] === null ? $resolved['content'] : $ctx->renderString($resolved['document']);
  49. }
  50. public function text(Call $call, RenderContext $ctx): string
  51. {
  52. return $this->rendered($call, $ctx);
  53. }
  54. public function plain(Call $call, RenderContext $ctx, Format $format): string
  55. {
  56. return $this->rendered($call, $ctx);
  57. }
  58. public function html(Call $call, RenderContext $ctx): string
  59. {
  60. $resolved = $this->resolved($call, $ctx);
  61. if ($resolved === null) {
  62. return '';
  63. }
  64. return $resolved['document'] === null ? e($resolved['content']) : $ctx->renderString($resolved['document']);
  65. }
  66. public function markdown(Call $call, RenderContext $ctx): string
  67. {
  68. return $this->rendered($call, $ctx);
  69. }
  70. }