HitItemDTO.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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'];
  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. $category = [];
  32. if (is_array($source['category'])) {
  33. $category = $source['category'];
  34. } else {
  35. $category = [$source['category']];
  36. }
  37. return new self(
  38. id: $source['id'],
  39. score: $data['_score'],
  40. title: $source['title']['pali'] ?? '',
  41. content: implode('', $contentArray),
  42. path: $source['path'] ?? '',
  43. category: $category,
  44. highlight: implode('', $highlightArray),
  45. );
  46. }
  47. /**
  48. * 提取 para 引用ID(核心逻辑🔥)
  49. */
  50. public function getParaId(): ?string
  51. {
  52. if (preg_match('/pali_para_(\d+)_(\d+)/', $this->id, $matches)) {
  53. return "{$matches[1]}-{$matches[2]}";
  54. }
  55. return null;
  56. }
  57. public function getParaLink(): ?string
  58. {
  59. $id = $this->getParaId();
  60. if (!$id) return null;
  61. return "{{para|id={$id}|title={$id}|style=reference}}";
  62. }
  63. }