IndexSearchSuggestionRequest.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Http\Requests\V3;
  3. use Closure;
  4. use Illuminate\Foundation\Http\FormRequest;
  5. /**
  6. * `GET /v3/search-suggestions`:搜索框的前缀补全。
  7. */
  8. class IndexSearchSuggestionRequest extends FormRequest
  9. {
  10. /** 可补全的字段(OpenSearchService::suggest 的字段标识符) */
  11. public const FIELDS = ['title_pali', 'title_zh', 'content_pali', 'content_zh'];
  12. public function authorize(): bool
  13. {
  14. return true;
  15. }
  16. /**
  17. * @return array<string, array<int, mixed>>
  18. */
  19. public function rules(): array
  20. {
  21. return [
  22. 'q' => ['required', 'string', 'max:100'],
  23. 'fields' => ['sometimes', 'string', 'max:100', function (string $attribute, mixed $value, Closure $fail): void {
  24. $unknown = array_diff(self::splitFields((string) $value), self::FIELDS);
  25. if ($unknown !== [] || self::splitFields((string) $value) === []) {
  26. $fail(__('validation.in', ['attribute' => $attribute]));
  27. }
  28. }],
  29. 'limit' => ['sometimes', 'integer', 'min:1', 'max:50'],
  30. ];
  31. }
  32. /**
  33. * 逗号分隔的字段列表,去空白、去空项、去重。
  34. *
  35. * @return list<string>
  36. */
  37. public static function splitFields(string $value): array
  38. {
  39. return array_values(array_unique(array_filter(
  40. array_map('trim', explode(',', $value)),
  41. fn (string $field) => $field !== '',
  42. )));
  43. }
  44. }