HitItemDTO.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\DTO\Search;
  3. class HitItemDTO
  4. {
  5. public function __construct(
  6. public string $id,
  7. public float $score,
  8. public string $content,
  9. public string $title,
  10. public string $path,
  11. public array $category,
  12. public string $highlight,
  13. ) {}
  14. public static function fromArray(array $data): self
  15. {
  16. $source = $data['_source'];
  17. $highlight = $data['highlight'] ?? null;
  18. $highlightArray = [];
  19. if (is_array($highlight)) {
  20. foreach ($highlight as $key => $value) {
  21. $highlightArray = array_merge($highlightArray, $value);
  22. }
  23. }
  24. $content = $source['content'];
  25. $contentArray = [];
  26. if (is_array($content)) {
  27. foreach ($content as $key => $value) {
  28. $contentArray[] = $value;
  29. }
  30. }
  31. $titleArray = [];
  32. if (is_array($source['title'])) {
  33. foreach ($source['title'] as $key => $value) {
  34. $titleArray[] = $value;
  35. }
  36. }
  37. $title = implode('', $titleArray);
  38. $category = [];
  39. if (is_array($source['category'])) {
  40. $category = $source['category'];
  41. } else {
  42. $category = [$source['category']];
  43. }
  44. return new self(
  45. id: $source['id'],
  46. score: $data['_score'],
  47. title: $title,
  48. content: implode('', $contentArray),
  49. path: $source['path'] ?? '',
  50. category: $category,
  51. highlight: implode('', $highlightArray),
  52. );
  53. }
  54. /**
  55. * 提取 para 引用ID(核心逻辑🔥)
  56. */
  57. public function getParaId(): ?string
  58. {
  59. if (preg_match('/pali_para_(\d+)_(\d+)/', $this->id, $matches)) {
  60. return "{$matches[1]}-{$matches[2]}";
  61. }
  62. return null;
  63. }
  64. public function getParaLink(): ?string
  65. {
  66. $id = $this->getParaId();
  67. if (!$id) return null;
  68. return "{{para|id={$id}|title={$id}|style=reference}}";
  69. }
  70. }