TplLoader.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Models\Article;
  4. use App\Services\Markup\Ir\Document;
  5. use App\Services\Markup\Ir\Scope;
  6. use Mustache\Engine as Mustache;
  7. /**
  8. * `{{Tpl:名字|…}}`:取标题为「Tpl:名字」的文章,用 Mustache 代入参数,结果按 markdown 解析成下一层内容。
  9. */
  10. final class TplLoader extends Loader
  11. {
  12. /** @var array<string, array{title: string, params: array<string, string>, scope: Scope}> */
  13. private array $pending = [];
  14. /** @var array<string, array{content: string, document: ?Document}|null> */
  15. private array $results = [];
  16. /**
  17. * @param array<string, string> $params
  18. */
  19. public function request(string $title, array $params, Scope $scope): string
  20. {
  21. // 层数进 key:模板正文里再用同一个模板时逐层展开,到最大层数为止
  22. $key = $title."\x1F".json_encode($params)."\x1F".$scope->depth;
  23. if (! array_key_exists($key, $this->results)) {
  24. $this->pending[$key] = ['title' => $title, 'params' => $params, 'scope' => $scope];
  25. }
  26. return $key;
  27. }
  28. /**
  29. * @return array{content: string, document: ?Document}|null
  30. */
  31. public function result(string $key): ?array
  32. {
  33. return $this->results[$key] ?? null;
  34. }
  35. public function hasPending(): bool
  36. {
  37. return $this->pending !== [];
  38. }
  39. public function load(): void
  40. {
  41. $batch = $this->pending;
  42. $this->pending = [];
  43. $articles = Article::whereIn('title', array_values(array_unique(array_column($batch, 'title'))))
  44. ->get(['title', 'content'])
  45. ->keyBy('title');
  46. $mustache = new Mustache(['entity_flags' => ENT_QUOTES, 'escape' => fn ($value) => $value]);
  47. foreach ($batch as $key => $request) {
  48. $article = $articles->get($request['title']);
  49. if ($article === null) {
  50. $this->results[$key] = null;
  51. continue;
  52. }
  53. $content = (string) $article->content;
  54. if ($request['params'] !== []) {
  55. $content = $mustache->render($content, $request['params']);
  56. }
  57. $document = null;
  58. if ($request['scope']->canNest()) {
  59. $document = $this->resolver->parser->parse($content, $request['scope']->nested(contentType: $request['scope']->contentType));
  60. $this->resolver->collect($document);
  61. }
  62. $this->results[$key] = ['content' => $content, 'document' => $document];
  63. }
  64. }
  65. }