AggregateTipitakaWordParagraphRequest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Http\Requests\V3;
  3. use Illuminate\Foundation\Http\FormRequest;
  4. /**
  5. * `GET /v3/tipitaka-word-paragraphs/aggregate`:按书统计命中。
  6. *
  7. * 也是列表端点 `IndexTipitakaWordParagraphRequest` 的基类——两者的检索条件相同,
  8. * 列表另有书的过滤与分页。
  9. */
  10. class AggregateTipitakaWordParagraphRequest extends FormRequest
  11. {
  12. /** 一次最多查多少个词形(一个常见词根展开后通常几十个) */
  13. public const MAX_WORDS = 200;
  14. public const BOLD = ['only', 'exclude'];
  15. public function authorize(): bool
  16. {
  17. return true;
  18. }
  19. /**
  20. * @return array<string, array<int, mixed>>
  21. */
  22. public function rules(): array
  23. {
  24. return [
  25. 'words' => ['required', 'string', 'max:6000', function (string $attribute, mixed $value, \Closure $fail): void {
  26. $count = count(self::splitWords((string) $value));
  27. if ($count === 0) {
  28. $fail(__('validation.required', ['attribute' => $attribute]));
  29. } elseif ($count > self::MAX_WORDS) {
  30. $fail(__('validation.max.array', ['attribute' => $attribute, 'max' => self::MAX_WORDS]));
  31. }
  32. }],
  33. 'bold' => ['sometimes', 'string', 'in:'.implode(',', self::BOLD)],
  34. ];
  35. }
  36. /**
  37. * 逗号分隔的词形 → 去空白、去空项、去重。
  38. *
  39. * 空串绝不能进查询:`real` 为空的行有四百多万,覆盖几十万个段落。
  40. *
  41. * @return list<string>
  42. */
  43. public static function splitWords(string $value): array
  44. {
  45. $words = array_map('trim', explode(',', $value));
  46. return array_values(array_unique(array_filter($words, fn (string $w): bool => $w !== '')));
  47. }
  48. /**
  49. * Service 用的检索条件。
  50. *
  51. * @return array{words: list<string>, bold: string|null}
  52. */
  53. public function criteria(): array
  54. {
  55. return [
  56. 'words' => self::splitWords((string) $this->validated('words')),
  57. 'bold' => $this->validated('bold'),
  58. ];
  59. }
  60. }