HitItemDTO.php 2.4 KB

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