TermLoader.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Models\DhammaTerm;
  4. use App\Services\ChannelService;
  5. use App\Services\Markup\Ir\Document;
  6. use App\Services\Markup\Ir\Scope;
  7. use Illuminate\Support\Collection;
  8. /**
  9. * 术语查询,口径同 v2 TemplateRender::getTermProps():
  10. *
  11. * 1. 这个 channel 自己的术语(最新的一条)
  12. * 2. channel 拥有者名下、不属于任何 channel 的术语:语言完全一致优先,其次同语族
  13. * 3. 社区术语 channel `_community_term_zh-hans_`
  14. *
  15. * 没有 channel(或 channel 不存在)时不查,只回显词头。tag 为空表示不按 tag 过滤。
  16. * 术语的 note 只展开一层:note 里出现的术语只查译名,不再取它们自己的 note。
  17. * 每个 channel 三次查询,与术语个数无关。
  18. */
  19. final class TermLoader extends Loader
  20. {
  21. private const COMMUNITY_CHANNEL = '_community_term_zh-hans_';
  22. /** @var array<string, array{word: string, tag: string, channel: ?string, depth: int, inTermNote: bool}> */
  23. private array $pending = [];
  24. /** @var array<string, array{term: ?DhammaTerm, community: bool, channel: ?string, studio: ?string, note: ?Document}> */
  25. private array $results = [];
  26. public function __construct(private readonly ChannelService $channelService) {}
  27. public function request(string $word, string $tag, ?string $channel, Scope $scope): string
  28. {
  29. // 层数进 key:note 里再引用同一个术语时,每层各有自己的结果,到最大层数为止(否则渲染时无限递归)
  30. $key = implode("\x1F", [$word, $tag, $channel ?? '', $scope->depth, (int) $scope->inTermNote]);
  31. if (! isset($this->results[$key])) {
  32. $this->pending[$key] = ['word' => $word, 'tag' => $tag, 'channel' => $channel, 'depth' => $scope->depth, 'inTermNote' => $scope->inTermNote];
  33. }
  34. return $key;
  35. }
  36. /**
  37. * @return array{term: ?DhammaTerm, community: bool, channel: ?string, studio: ?string, note: ?Document}
  38. */
  39. public function result(string $key): array
  40. {
  41. return $this->results[$key] ?? ['term' => null, 'community' => false, 'channel' => null, 'studio' => null, 'note' => null];
  42. }
  43. public function hasPending(): bool
  44. {
  45. return $this->pending !== [];
  46. }
  47. public function load(): void
  48. {
  49. $batch = $this->pending;
  50. $this->pending = [];
  51. $byChannel = [];
  52. foreach ($batch as $key => $request) {
  53. $byChannel[$request['channel'] ?? ''][$key] = $request;
  54. }
  55. $community = null;
  56. foreach ($byChannel as $channelUid => $requests) {
  57. $channel = $this->resolver->channels()->get($channelUid === '' ? null : $channelUid);
  58. if ($channel === null) {
  59. // 没给 channel:不查。给了但 channel 已不存在(被删):只查社区术语(v2 口径)
  60. $community = $channelUid === '' ? null : ($community ?? $this->communityTerms(array_column($batch, 'word')));
  61. foreach ($requests as $key => $request) {
  62. $term = $community === null ? null : $this->first($community, $request);
  63. $this->results[$key] = [
  64. 'term' => $term,
  65. 'community' => $term !== null,
  66. 'channel' => $request['channel'],
  67. 'studio' => null,
  68. 'note' => $request['inTermNote'] ? null : $this->note($term, $channelUid, $request['depth']),
  69. ];
  70. }
  71. continue;
  72. }
  73. $words = array_values(array_unique(array_column($requests, 'word')));
  74. $own = DhammaTerm::whereIn('word', $words)->where('channal', $channelUid)
  75. ->orderByDesc('updated_at')->get();
  76. $studio = DhammaTerm::whereIn('word', $words)->where('owner', $channel->owner_uid)
  77. ->where(fn ($query) => $query->whereNull('channal')->orWhere('channal', ''))
  78. ->orderByDesc('updated_at')->get();
  79. $community ??= $this->communityTerms(array_column($batch, 'word'));
  80. foreach ($requests as $key => $request) {
  81. $term = $this->first($own, $request);
  82. $isCommunity = false;
  83. if ($term === null) {
  84. $term = $this->bestByLanguage($studio, $request, (string) $channel->lang);
  85. }
  86. if ($term === null) {
  87. $term = $this->first($community, $request);
  88. $isCommunity = $term !== null;
  89. }
  90. $this->results[$key] = [
  91. 'term' => $term,
  92. 'community' => $isCommunity,
  93. 'channel' => $channelUid,
  94. 'studio' => (string) $channel->owner_uid,
  95. 'note' => $request['inTermNote'] ? null : $this->note($term, $channelUid, $request['depth']),
  96. ];
  97. }
  98. }
  99. }
  100. /**
  101. * @param list<string> $words
  102. * @return Collection<int, DhammaTerm>
  103. */
  104. private function communityTerms(array $words): Collection
  105. {
  106. $uid = $this->channelService->systemUid(self::COMMUNITY_CHANNEL);
  107. if ($uid === false) {
  108. return new Collection;
  109. }
  110. return DhammaTerm::whereIn('word', array_values(array_unique($words)))->where('channal', $uid)
  111. ->orderByDesc('updated_at')->get();
  112. }
  113. /**
  114. * @param Collection<int, DhammaTerm> $terms
  115. * @param array{word: string, tag: string} $request
  116. */
  117. private function first(Collection $terms, array $request): ?DhammaTerm
  118. {
  119. return $terms->first(fn (DhammaTerm $term) => $this->matches($term, $request));
  120. }
  121. /**
  122. * 语言完全一致记 2 分、同语族记 1 分,取分高的;同分取最新的。
  123. *
  124. * @param Collection<int, DhammaTerm> $terms
  125. * @param array{word: string, tag: string} $request
  126. */
  127. private function bestByLanguage(Collection $terms, array $request, string $lang): ?DhammaTerm
  128. {
  129. $family = explode('-', $lang)[0];
  130. $best = null;
  131. $bestScore = 0;
  132. foreach ($terms as $term) {
  133. if (! $this->matches($term, $request)) {
  134. continue;
  135. }
  136. $language = (string) $term->language;
  137. $score = $language === $lang ? 2 : ($family !== '' && str_contains($language, $family) ? 1 : 0);
  138. if ($score > $bestScore) {
  139. [$best, $bestScore] = [$term, $score];
  140. }
  141. }
  142. return $best;
  143. }
  144. /**
  145. * @param array{word: string, tag: string} $request
  146. */
  147. private function matches(DhammaTerm $term, array $request): bool
  148. {
  149. return $term->word === $request['word'] && ($request['tag'] === '' || $term->tag === $request['tag']);
  150. }
  151. private function note(?DhammaTerm $term, string $channelUid, int $depth): ?Document
  152. {
  153. $note = (string) ($term?->note ?? '');
  154. $scope = new Scope(channels: [$channelUid], depth: $depth);
  155. if (trim($note) === '' || ! $scope->canNest()) {
  156. return null;
  157. }
  158. $nested = $scope->nested(contentType: $term->getAttribute('content_type') ?? 'markdown');
  159. // note 里的术语不再展开它们自己的 note:一层就够(v2 也只展开一层),否则词条正文互相引用会成倍膨胀
  160. $document = $this->resolver->parser->parse(
  161. $note,
  162. new Scope($nested->channels, $nested->dialect, $nested->depth, $nested->channelType, $nested->contentType, inTermNote: true),
  163. );
  164. $this->resolver->collect($document);
  165. return $document;
  166. }
  167. }