GlossaryService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\DhammaTerm;
  4. use App\Services\ChannelService as ChannelLookup;
  5. use Illuminate\Support\Collection;
  6. /**
  7. * 术语词汇表(只读):语法术语表与社区译名表,客户端启动时整表拉取后本地查。
  8. *
  9. * 取代 v2 `term-vocabulary`(`TermVocabularyController`)。数据就是两个系统 channel 里的术语:
  10. * - grammar:`_System_Grammar_Term_{lang}_`
  11. * - community:`_community_term_{lang}_`
  12. * 该语言的 channel 不存在时回退到英文(与 v2 相同)。注意它与批注的 `glossary` 类型(外挂术语)不是一回事。
  13. */
  14. class GlossaryService
  15. {
  16. public const KINDS = ['grammar', 'community'];
  17. private const CHANNEL_PREFIX = [
  18. 'grammar' => '_System_Grammar_Term_',
  19. 'community' => '_community_term_',
  20. ];
  21. private const FALLBACK_LANG = 'en';
  22. public function __construct(private readonly ChannelLookup $channels) {}
  23. /**
  24. * 某种词汇表的全部条目(按词排序),以及实际用到的语言。
  25. *
  26. * @return array{items: Collection<int, DhammaTerm>, lang: string}
  27. */
  28. public function entries(string $kind, string $lang): array
  29. {
  30. $prefix = self::CHANNEL_PREFIX[$kind];
  31. $served = $lang;
  32. $channel = $this->channels->systemUid($prefix.strtolower($lang).'_');
  33. if ($channel === false) {
  34. $served = self::FALLBACK_LANG;
  35. $channel = $this->channels->systemUid($prefix.self::FALLBACK_LANG.'_');
  36. }
  37. $items = $channel === false
  38. ? collect()
  39. : DhammaTerm::query()
  40. ->where('channal', $channel)
  41. ->whereNotNull('word')
  42. ->where('word', '<>', '')
  43. ->orderBy('word')
  44. ->orderBy('guid')
  45. ->get(['guid', 'word', 'tag', 'meaning', 'other_meaning']);
  46. return ['items' => $items, 'lang' => $served];
  47. }
  48. }