PaliWordSuggestionService.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\WordIndex;
  4. use Illuminate\Contracts\Database\Eloquent\Builder;
  5. /**
  6. * 巴利词的前缀补全(`word_indices`:三藏里出现过的每个词形及出现次数、黑体次数)。
  7. *
  8. * 前缀同时匹配原形与去变音形(`word_en`),所以不打变音符号也能补全(dhamma → dhammā)。
  9. * 排序:与输入完全相同的词在前,其余按出现次数降序(v2 按词长排,短而罕见的词形挤掉常用词)。
  10. */
  11. class PaliWordSuggestionService
  12. {
  13. /**
  14. * @return list<array{word: string, count: int, bold: int}>
  15. */
  16. public function suggest(string $prefix, int $limit): array
  17. {
  18. $prefix = mb_strtolower(trim($prefix), 'UTF-8');
  19. $like = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $prefix).'%';
  20. return WordIndex::query()
  21. ->where(fn (Builder $q) => $q->where('word', 'like', $like)->orWhere('word_en', 'like', $like))
  22. ->orderByRaw('(word = ? or word_en = ?) desc', [$prefix, $prefix])
  23. ->orderByDesc('count')
  24. ->orderBy('word')
  25. ->limit($limit)
  26. ->get(['word', 'count', 'bold'])
  27. ->map(fn (WordIndex $w) => [
  28. 'word' => (string) $w->word,
  29. 'count' => (int) $w->count,
  30. 'bold' => (int) $w->bold,
  31. ])
  32. ->all();
  33. }
  34. }