TemplateRender.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Services;
  3. use App\Services\Templates\TemplateInterface;
  4. use InvalidArgumentException;
  5. class TemplateRender
  6. {
  7. protected string $templateName;
  8. protected array $params = [];
  9. protected TemplateInterface $template;
  10. // 定义默认公共参数
  11. protected array $options = [
  12. 'format' => 'react', // 默认格式为 react
  13. ];
  14. public static function name(string $templateName): self
  15. {
  16. $instance = new self();
  17. $instance->templateName = $templateName;
  18. return $instance;
  19. }
  20. public function param(array $params): self
  21. {
  22. $this->params = $params;
  23. return $this;
  24. }
  25. public function options(array $options): self
  26. {
  27. $this->options = $options;
  28. return $this;
  29. }
  30. public function render(): array
  31. {
  32. // 解析模板类
  33. $this->resolveTemplate();
  34. // 设置参数并渲染
  35. return $this->template
  36. ->setParams($this->params)
  37. ->setOptions($this->options)
  38. ->render();
  39. }
  40. protected function resolveTemplate(): void
  41. {
  42. // 模板名称到类的映射(可以用配置文件替代)
  43. $templateMap = [
  44. 'cf' => \App\Services\Templates\ConfidenceTemplate::class,
  45. 'nissaya' => \App\Services\Templates\NissayaTemplate::class,
  46. 'term' => \App\Services\Templates\TermTemplate::class,
  47. 'note' => \App\Services\Templates\NoteTemplate::class,
  48. ];
  49. if (!isset($templateMap[$this->templateName])) {
  50. throw new InvalidArgumentException("Template {$this->templateName} not found.");
  51. }
  52. // 通过服务容器解析模板类
  53. $this->template = app($templateMap[$this->templateName]);
  54. }
  55. }