NissayaCardService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\DhammaTerm;
  4. use App\Models\NissayaEnding;
  5. use App\Models\Relation;
  6. use App\Services\ChannelService as ChannelLookup;
  7. use App\Services\Markup\Format;
  8. use App\Services\Markup\MarkupService;
  9. use App\Services\Markup\RenderOptions;
  10. use Illuminate\Support\Collection;
  11. /**
  12. * 缅文 nissaya 词尾卡片(只读):这个词尾对应的语法术语,以及它表达的语法关系。
  13. *
  14. * 取代 v2 `nissaya-card/{ending}`(`NissayaCardController@show`)。数据:
  15. * - 术语取语法术语系统 channel `_System_Grammar_Term_{lang}_`,没有就用 en(与 v2 相同)
  16. * - 词尾 → 关系:`nissaya_endings.relation`;关系的格位 / 分类:`relations`
  17. * - 翻译建议:同一关系在 `lang` 下的其它词尾(from 为空或与关系的 from 相同)
  18. *
  19. * 与 v2 的差别:只给结构化数据(v2 另有 mustache 渲染的 markdown 分支,表头文字也写死在后端);
  20. * 不再拼 dashboard 链接(前端自己拼);术语一次批量查(v2 逐个格位查,N+1);
  21. * 词尾说明用新渲染器给节点树(v2 是旧渲染器的 HTML)。
  22. */
  23. class NissayaCardService
  24. {
  25. private const GRAMMAR_CHANNEL = '_System_Grammar_Term_';
  26. public function __construct(
  27. private readonly ChannelLookup $channels,
  28. private readonly MarkupService $markup,
  29. ) {}
  30. /**
  31. * @return array{
  32. * ending: string,
  33. * lang: string,
  34. * term: array{id: string, word: string, tag: string|null, meaning: string, body: list<array<string, mixed>>}|null,
  35. * relations: list<array{
  36. * relation: string,
  37. * relation_label: string|null,
  38. * from: array{cases: list<array{case: string, label: string|null}>, spell: string|null}|null,
  39. * to: array{cases: list<array{case: string, label: string|null}>, spell: string|null}|null,
  40. * category: array{name: string, meaning: string, note: string}|null,
  41. * local_endings: list<string>
  42. * }>
  43. * }
  44. */
  45. public function card(string $ending, string $lang): array
  46. {
  47. [$channel, $servedLang] = $this->grammarChannel($lang);
  48. $relationNames = NissayaEnding::where('ending', $ending)
  49. ->whereNotNull('relation')
  50. ->where('relation', '<>', '')
  51. ->pluck('relation')
  52. ->unique()
  53. ->values();
  54. $relations = $relationNames->isEmpty()
  55. ? collect()
  56. : Relation::whereIn('name', $relationNames)->orderBy('name')->get(['name', 'from', 'to', 'category']);
  57. // 一次查出卡片上要用的全部术语:词尾、关系名、格位、分类
  58. $words = collect([$ending])
  59. ->merge($relations->pluck('name'))
  60. ->merge($relations->pluck('category')->filter())
  61. ->merge($relations->flatMap(fn (Relation $r) => [
  62. ...($this->decode($r->from)['case'] ?? []),
  63. ...($this->decode($r->to)['case'] ?? []),
  64. ]))
  65. ->filter(fn ($w) => is_string($w) && $w !== '')
  66. ->unique()
  67. ->values();
  68. $terms = $channel === false || $words->isEmpty()
  69. ? collect()
  70. : DhammaTerm::where('channal', $channel)->whereIn('word', $words)
  71. ->get(['guid', 'word', 'tag', 'meaning', 'note', 'content_type', 'channal'])
  72. ->keyBy('word');
  73. $localEndings = $relations->isEmpty()
  74. ? collect()
  75. : NissayaEnding::whereIn('relation', $relations->pluck('name'))
  76. ->where('lang', $lang)
  77. ->get(['ending', 'relation', 'from']);
  78. $rendered = $this->render($terms->get($ending), $relations, $terms);
  79. return [
  80. 'ending' => $ending,
  81. 'lang' => $servedLang,
  82. 'term' => $this->termOf($terms->get($ending), $rendered['body']),
  83. 'relations' => $relations->map(fn (Relation $relation) => $this->relationRow(
  84. $relation,
  85. $terms,
  86. $localEndings,
  87. $rendered['categories'],
  88. ))->values()->all(),
  89. ];
  90. }
  91. /**
  92. * @return array{0: string|false, 1: string} 语法术语 channel 的 uid 与实际用到的语言
  93. */
  94. private function grammarChannel(string $lang): array
  95. {
  96. $channel = $this->channels->systemUid(self::GRAMMAR_CHANNEL.strtolower($lang).'_');
  97. if ($channel !== false) {
  98. return [$channel, $lang];
  99. }
  100. return [$this->channels->systemUid(self::GRAMMAR_CHANNEL.'en_'), 'en'];
  101. }
  102. /**
  103. * 词尾说明(节点树)与各分类说明(纯文本)一次渲染。
  104. *
  105. * @param Collection<int, Relation> $relations
  106. * @param Collection<string, DhammaTerm> $terms
  107. * @return array{body: list<array<string, mixed>>, categories: array<string, string>}
  108. */
  109. private function render(?DhammaTerm $endingTerm, Collection $relations, Collection $terms): array
  110. {
  111. $tree = [];
  112. if ($endingTerm && trim((string) $endingTerm->note) !== '') {
  113. $tree['ending'] = $this->item($endingTerm);
  114. }
  115. $text = [];
  116. foreach ($relations->pluck('category')->filter()->unique() as $name) {
  117. $term = $terms->get($name);
  118. if ($term && trim((string) $term->note) !== '') {
  119. $text[$name] = $this->item($term);
  120. }
  121. }
  122. return [
  123. 'body' => $tree === [] ? [] : $this->markup->renderMany($tree, new RenderOptions(format: Format::Tree))['ending'],
  124. 'categories' => $text === [] ? [] : array_map('strval', $this->markup->renderMany($text, new RenderOptions(format: Format::Text))),
  125. ];
  126. }
  127. /**
  128. * @return array{source: string, channels: list<string>, contentType: string}
  129. */
  130. private function item(DhammaTerm $term): array
  131. {
  132. return [
  133. 'source' => (string) $term->note,
  134. 'channels' => $term->channal ? [$term->channal] : [],
  135. 'contentType' => $term->effectiveContentType(),
  136. ];
  137. }
  138. /**
  139. * @param list<array<string, mixed>> $body
  140. * @return array{id: string, word: string, tag: string|null, meaning: string, body: list<array<string, mixed>>}|null
  141. */
  142. private function termOf(?DhammaTerm $term, array $body): ?array
  143. {
  144. if ($term === null) {
  145. return null;
  146. }
  147. $tag = trim((string) $term->tag);
  148. return [
  149. 'id' => (string) $term->guid,
  150. 'word' => (string) $term->word,
  151. 'tag' => $tag === '' ? null : $tag,
  152. 'meaning' => (string) $term->meaning,
  153. 'body' => $body,
  154. ];
  155. }
  156. /**
  157. * @param Collection<string, DhammaTerm> $terms
  158. * @param Collection<int, NissayaEnding> $localEndings
  159. * @param array<string, string> $categoryNotes
  160. * @return array{relation: string, relation_label: string|null, from: array{cases: list<array{case: string, label: string|null}>, spell: string|null}|null, to: array{cases: list<array{case: string, label: string|null}>, spell: string|null}|null, category: array{name: string, meaning: string, note: string}|null, local_endings: list<string>}
  161. */
  162. private function relationRow(Relation $relation, Collection $terms, Collection $localEndings, array $categoryNotes): array
  163. {
  164. $category = null;
  165. if (! empty($relation->category)) {
  166. $term = $terms->get($relation->category);
  167. $category = [
  168. 'name' => (string) $relation->category,
  169. 'meaning' => $term ? (string) $term->meaning : (string) $relation->category,
  170. 'note' => trim($categoryNotes[$relation->category] ?? ($term ? '' : (string) $relation->category)),
  171. ];
  172. }
  173. // 翻译建议:同一关系、该语言的词尾;词尾的 from 为空,或与关系的 from 完全相同(与 v2 一致,比较 JSON 原文)
  174. $suggestions = $localEndings
  175. ->filter(fn (NissayaEnding $e) => $e->relation === $relation->name
  176. && (empty($e->from) || $this->raw($e->from) === $this->raw($relation->from)))
  177. ->pluck('ending')
  178. ->unique()
  179. ->values()
  180. ->all();
  181. return [
  182. 'relation' => (string) $relation->name,
  183. 'relation_label' => $terms->get($relation->name)?->meaning,
  184. 'from' => $this->side($relation->from, $terms),
  185. 'to' => $this->side($relation->to, $terms),
  186. 'category' => $category,
  187. 'local_endings' => $suggestions,
  188. ];
  189. }
  190. /**
  191. * 关系的一端(from / to):格位(带本地译名)与拼写。都没有返回 null。
  192. *
  193. * @param Collection<string, DhammaTerm> $terms
  194. * @return array{cases: list<array{case: string, label: string|null}>, spell: string|null}|null
  195. */
  196. private function side(mixed $value, Collection $terms): ?array
  197. {
  198. $data = $this->decode($value);
  199. $cases = array_values(array_filter((array) ($data['case'] ?? []), 'is_string'));
  200. $spell = isset($data['spell']) && $data['spell'] !== '' ? (string) $data['spell'] : null;
  201. if ($cases === [] && $spell === null) {
  202. return null;
  203. }
  204. return [
  205. 'cases' => array_map(fn (string $case) => ['case' => $case, 'label' => $terms->get($case)?->meaning], $cases),
  206. 'spell' => $spell,
  207. ];
  208. }
  209. /**
  210. * json 列可能是字符串(库里原样)或已解码的数组。
  211. *
  212. * @return array<string, mixed>
  213. */
  214. private function decode(mixed $value): array
  215. {
  216. if (is_array($value)) {
  217. return $value;
  218. }
  219. $decoded = json_decode((string) $value, true);
  220. return is_array($decoded) ? $decoded : [];
  221. }
  222. private function raw(mixed $value): string
  223. {
  224. return is_string($value) ? $value : (string) json_encode($value);
  225. }
  226. }