TemplateRender.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. ];
  48. if (!isset($templateMap[$this->templateName])) {
  49. throw new InvalidArgumentException("Template {$this->templateName} not found.");
  50. }
  51. // 通过服务容器解析模板类
  52. $this->template = app($templateMap[$this->templateName]);
  53. }
  54. }