Resolver.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Services\Markup\Ir\Call;
  4. use App\Services\Markup\Ir\Document;
  5. use App\Services\Markup\Ir\Element;
  6. use App\Services\Markup\Ir\Node;
  7. use App\Services\Markup\Parsing\MarkupParser;
  8. use App\Services\Markup\RenderOptions;
  9. /**
  10. * 一次渲染的取数中心:遍历 IR 让每个模板登记要查的键,再按 loader 批量查。
  11. *
  12. * 一章几百个术语、几百个句子,各查一次(加上回退查询)而不是每个模板各查几次。
  13. */
  14. final class Resolver
  15. {
  16. /** 取数轮数上限:文章 → 句子 → 术语 note → … 每层一轮,正常两三轮就停 */
  17. private const MAX_ROUNDS = 10;
  18. /** @var array<class-string<Loader>, Loader> */
  19. private array $loaders = [];
  20. private ChannelDirectory $channels;
  21. public function __construct(
  22. public readonly RenderOptions $options,
  23. public readonly MarkupParser $parser,
  24. ) {
  25. $this->channels = new ChannelDirectory;
  26. }
  27. /**
  28. * @template T of Loader
  29. *
  30. * @param class-string<T> $class
  31. * @return T
  32. */
  33. public function loader(string $class): Loader
  34. {
  35. if (! isset($this->loaders[$class])) {
  36. $loader = app()->make($class);
  37. $loader->setResolver($this);
  38. $this->loaders[$class] = $loader;
  39. }
  40. /** @var T */
  41. return $this->loaders[$class];
  42. }
  43. public function channels(): ChannelDirectory
  44. {
  45. return $this->channels;
  46. }
  47. public function collect(Document $document): void
  48. {
  49. $this->channels->request($document->scope->channels);
  50. $this->collectNodes($document->nodes);
  51. }
  52. /**
  53. * @param list<Node> $nodes
  54. */
  55. private function collectNodes(array $nodes): void
  56. {
  57. foreach ($nodes as $node) {
  58. if ($node instanceof Element) {
  59. $this->collectNodes($node->children);
  60. } elseif ($node instanceof Call) {
  61. $node->template->collect($node, $this);
  62. foreach ($node->slots as $slot) {
  63. $this->collect($slot);
  64. }
  65. }
  66. }
  67. }
  68. public function run(): void
  69. {
  70. for ($round = 0; $round < self::MAX_ROUNDS; $round++) {
  71. $pending = array_filter($this->loaders, fn (Loader $loader) => $loader->hasPending());
  72. if ($pending === []) {
  73. return;
  74. }
  75. foreach ($pending as $loader) {
  76. $loader->load();
  77. }
  78. }
  79. }
  80. }