SentenceLoader.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. <?php
  2. namespace App\Services\Markup\Resolve;
  3. use App\Models\CustomBook;
  4. use App\Models\Sentence;
  5. use App\Services\ChannelService;
  6. use App\Services\Markup\Ir\Document;
  7. use App\Services\Markup\Ir\Scope;
  8. /**
  9. * 句子模板的取数:按坐标取若干 channel 的句子,正文解析成下一层内容。
  10. *
  11. * channel 口径同 v2 CorpusController::getSentTpl():调用方给的 channel,再加原文 channel——
  12. * 三藏(book < 1000)阅读模式是 `_System_Pali_VRI_`、编辑模式是 `_System_Wbw_VRI_`;自定义书是该书的 channel。
  13. * 所有句子一次查完(按段落分组 OR)。
  14. *
  15. * 只取渲染要用的字段。编辑器还要的 editor / studio / suggestionCount 等不在这里——
  16. * 那是编辑接口的契约,迁编辑模式时在 v3 另做。
  17. */
  18. final class SentenceLoader extends Loader
  19. {
  20. /** @var array<string, array{id: string, channels: list<string>, mode: string, depth: int}> */
  21. private array $pending = [];
  22. /** @var array<string, array<string, mixed>|null> */
  23. private array $results = [];
  24. public function __construct(private readonly ChannelService $channelService) {}
  25. /**
  26. * @param list<string> $channels
  27. */
  28. public function request(string $id, array $channels, string $mode, Scope $scope): string
  29. {
  30. // 层数进 key:句子正文里再引用同一个句子时,每层各有自己的结果,到最大层数为止(否则渲染时无限递归)
  31. $key = implode("\x1F", [$id, implode(',', $channels), $mode, $scope->depth]);
  32. if (! array_key_exists($key, $this->results)) {
  33. $this->pending[$key] = ['id' => $id, 'channels' => $channels, 'mode' => $mode, 'depth' => $scope->depth];
  34. }
  35. return $key;
  36. }
  37. /**
  38. * @return array{book: int, para: int, wordStart: int, wordEnd: int, origin: list<array<string, mixed>>, translation: list<array<string, mixed>>, commentaries: list<array<string, mixed>>}|null
  39. */
  40. public function result(string $key): ?array
  41. {
  42. return $this->results[$key] ?? null;
  43. }
  44. public function hasPending(): bool
  45. {
  46. return $this->pending !== [];
  47. }
  48. public function load(): void
  49. {
  50. $batch = $this->pending;
  51. $this->pending = [];
  52. $requests = [];
  53. foreach ($batch as $key => $request) {
  54. $parts = explode('-', $request['id']);
  55. if (count($parts) !== 4 || array_filter($parts, fn ($part) => ! ctype_digit(trim($part))) !== []) {
  56. $this->results[$key] = null;
  57. continue;
  58. }
  59. $requests[$key] = $request + ['coords' => array_map('intval', $parts)];
  60. }
  61. if ($requests === []) {
  62. return;
  63. }
  64. $customBooks = $this->customBookChannels($requests);
  65. $channelsByKey = [];
  66. $allChannels = [];
  67. $paragraphs = [];
  68. foreach ($requests as $key => $request) {
  69. [$book, $para] = $request['coords'];
  70. $origin = $book < 1000
  71. ? $this->channelService->systemUid($request['mode'] === 'read' ? '_System_Pali_VRI_' : '_System_Wbw_VRI_')
  72. : ($customBooks[$book] ?? false);
  73. $channels = $request['channels'];
  74. if ($origin !== false && $origin !== null) {
  75. $channels[] = (string) $origin;
  76. }
  77. $channels = array_values(array_unique($channels));
  78. $channelsByKey[$key] = $channels;
  79. array_push($allChannels, ...$channels);
  80. $paragraphs["{$book}-{$para}"] = [$book, $para];
  81. }
  82. $this->resolver->channels()->request($allChannels);
  83. $rows = Sentence::query()
  84. ->where(function ($query) use ($paragraphs) {
  85. foreach ($paragraphs as [$book, $para]) {
  86. $query->orWhere(fn ($where) => $where->where('book_id', $book)->where('paragraph', $para));
  87. }
  88. })
  89. ->whereIn('channel_uid', array_values(array_unique($allChannels)))
  90. ->get(['uid', 'book_id', 'paragraph', 'word_start', 'word_end', 'channel_uid', 'content', 'content_type'])
  91. ->keyBy(fn (Sentence $row) => "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}@{$row->channel_uid}");
  92. foreach ($requests as $key => $request) {
  93. [$book, $para, $start, $end] = $request['coords'];
  94. $result = [
  95. 'book' => $book, 'para' => $para, 'wordStart' => $start, 'wordEnd' => $end,
  96. 'origin' => [], 'translation' => [], 'commentaries' => [],
  97. ];
  98. foreach ($channelsByKey[$key] as $channelUid) {
  99. $row = $rows->get("{$book}-{$para}-{$start}-{$end}@{$channelUid}");
  100. $channel = $this->resolver->channels()->get($channelUid);
  101. if ($row === null || $channel === null) {
  102. continue;
  103. }
  104. $entry = [
  105. 'id' => (string) $row->uid,
  106. 'channel' => [
  107. 'id' => (string) $channel->uid,
  108. 'name' => (string) $channel->name,
  109. 'type' => (string) $channel->type,
  110. 'lang' => (string) $channel->lang,
  111. ],
  112. 'contentType' => (string) $row->content_type,
  113. 'content' => (string) $row->content,
  114. 'body' => $this->body($row, (string) $channel->type, $request),
  115. ];
  116. $area = match ((string) $channel->type) {
  117. 'original', 'wbw' => 'origin',
  118. 'commentary' => 'commentaries',
  119. default => 'translation',
  120. };
  121. $result[$area][] = $entry;
  122. }
  123. $this->results[$key] = $result;
  124. }
  125. }
  126. /**
  127. * 句子正文 → 下一层内容。逐词解析的 json(非 nissaya channel)不是标记文本,不解析。
  128. *
  129. * @param array{channels: list<string>, depth: int} $request
  130. */
  131. private function body(Sentence $row, string $channelType, array $request): ?Document
  132. {
  133. $parent = new Scope(channels: $request['channels'], depth: $request['depth']);
  134. if (! $parent->canNest() || ($row->content_type === 'json' && $channelType !== 'nissaya')) {
  135. return null;
  136. }
  137. // 义注 channel 的正文按全部 channel 渲染(v2 口径),其余按本句的 channel
  138. $channels = $channelType === 'commentary' ? $request['channels'] : [(string) $row->channel_uid];
  139. $document = $this->resolver->parser->parse(
  140. (string) $row->content,
  141. $parent->nested($channels, (string) $row->content_type, $channelType === 'nissaya' ? 'nissaya' : 'translation'),
  142. );
  143. $this->resolver->collect($document);
  144. return $document;
  145. }
  146. /**
  147. * 自定义书(book ≥ 1000)的原文 channel。
  148. *
  149. * @param array<string, array{coords: list<int>}> $requests
  150. * @return array<int, string>
  151. */
  152. private function customBookChannels(array $requests): array
  153. {
  154. $books = array_values(array_unique(array_filter(
  155. array_map(fn ($request) => $request['coords'][0], $requests),
  156. fn (int $book) => $book >= 1000,
  157. )));
  158. if ($books === []) {
  159. return [];
  160. }
  161. return CustomBook::whereIn('book_id', $books)->pluck('channel_id', 'book_id')
  162. ->map(fn ($uid) => (string) $uid)->all();
  163. }
  164. }