SearchController.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Http\Controllers\Library;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use App\Services\OpenSearchService;
  6. use App\DTO\Search\SearchDataDTO;
  7. class SearchController extends Controller
  8. {
  9. public function search(Request $request)
  10. {
  11. $query = trim($request->input('q', ''));
  12. $category = $request->input('category', 'all');
  13. $page = max(1, (int) $request->input('page', 1));
  14. $perPage = 10;
  15. $lang = $request->input('lang');
  16. $search = app(OpenSearchService::class);
  17. // 组装搜索参数
  18. $params = [
  19. 'query' => $query,
  20. 'pageSize' => $perPage,
  21. 'page' => $page,
  22. 'language' => $lang,
  23. 'resourceType' => $request->input('type'),
  24. ];
  25. $result = $search->search($params);
  26. $dto = SearchDataDTO::fromArray($result);
  27. $results = [];
  28. foreach ($dto->hits->items as $key => $item) {
  29. $results[] = [
  30. 'word' => 'word',
  31. 'zh' => $item->title,
  32. 'lang' => 'pi',
  33. 'category' => '法义术语',
  34. 'quality' => 'featured',
  35. 'snippet' => $item->highlight,
  36. 'updated' => '2025-11-12',
  37. ];
  38. }
  39. $category = $dto->aggregations->category->buckets;
  40. // 分页对象(兼容 Blade paginator 风格)
  41. $pagination = [
  42. 'total' => $dto->hits->total,
  43. 'per_page' => $perPage,
  44. 'current_page' => $page,
  45. 'last_page' => max(1, (int) ceil($dto->hits->total / $perPage)),
  46. ];
  47. return view('wiki.search', [
  48. 'lang' => $lang,
  49. 'query' => $query,
  50. 'results' => $results,
  51. 'pagination' => $pagination,
  52. 'category' => 'all',
  53. 'filters' => $category,
  54. 'categories' => $this->types(),
  55. 'recentUpdates' => [],
  56. ]);
  57. }
  58. // ── Helpers ──────────────────────────────────────────────────
  59. private function types(): array
  60. {
  61. return [
  62. ['slug' => 'all', 'label' => '全部'],
  63. ['slug' => 'term', 'label' => '法义术语'],
  64. ['slug' => 'original_text', 'label' => '原文'],
  65. ['slug' => 'translation', 'label' => '译文'],
  66. ['slug' => 'article', 'label' => '文章'],
  67. ['slug' => 'course', 'label' => '课程'],
  68. ['slug' => 'dictionary', 'label' => '字典'],
  69. ];
  70. }
  71. }