@@ -51,13 +51,13 @@ public function search(Search $search): Result
51
51
$ data = $ this ->client ->collections [$ search ->index ->name ]->documents [$ search ->filters [0 ]->identifier ]->retrieve ();
52
52
} catch (ObjectNotFound ) {
53
53
return new Result (
54
- $ this ->hitsToDocuments ($ search ->index , []),
54
+ $ this ->hitsToDocuments ($ search ->index , [], [] ),
55
55
0 ,
56
56
);
57
57
}
58
58
59
59
return new Result (
60
- $ this ->hitsToDocuments ($ search ->index , [['document ' => $ data ]]),
60
+ $ this ->hitsToDocuments ($ search ->index , [['document ' => $ data ]], [] ),
61
61
1 ,
62
62
);
63
63
}
@@ -95,24 +95,55 @@ public function search(Search $search): Result
95
95
$ searchParams ['sort_by ' ] = \implode (', ' , $ sortBys );
96
96
}
97
97
98
+ if ([] !== $ search ->highlightFields ) {
99
+ $ searchParams ['highlight_fields ' ] = \implode (', ' , $ search ->highlightFields );
100
+ $ searchParams ['highlight_start_tag ' ] = $ search ->highlightPreTag ;
101
+ $ searchParams ['highlight_end_tag ' ] = $ search ->highlightPostTag ;
102
+ }
103
+
98
104
$ data = $ this ->client ->collections [$ search ->index ->name ]->documents ->search ($ searchParams );
99
105
100
106
return new Result (
101
- $ this ->hitsToDocuments ($ search ->index , $ data ['hits ' ]),
107
+ $ this ->hitsToDocuments ($ search ->index , $ data ['hits ' ], $ search -> highlightFields ),
102
108
$ data ['found ' ] ?? null ,
103
109
);
104
110
}
105
111
106
112
/**
107
113
* @param iterable<array<string, mixed>> $hits
114
+ * @param array<string> $highlightFields
108
115
*
109
116
* @return \Generator<int, array<string, mixed>>
110
117
*/
111
- private function hitsToDocuments (Index $ index , iterable $ hits ): \Generator
118
+ private function hitsToDocuments (Index $ index , iterable $ hits, array $ highlightFields ): \Generator
112
119
{
113
- /** @var array{document: array<string, mixed>} $hit */
120
+ /** @var array{document: array<string, mixed>, highlight?: array<string, array{snippet: string}> } $hit */
114
121
foreach ($ hits as $ hit ) {
115
- yield $ this ->marshaller ->unmarshall ($ index ->fields , $ hit ['document ' ]);
122
+ $ document = $ this ->marshaller ->unmarshall ($ index ->fields , $ hit ['document ' ]);
123
+
124
+ if ([] === $ highlightFields ) {
125
+ yield $ document ;
126
+
127
+ continue ;
128
+ }
129
+
130
+ $ document ['_formatted ' ] ??= [];
131
+
132
+ \assert (
133
+ \is_array ($ document ['_formatted ' ]),
134
+ 'Document with key "_formatted" expected to be array. ' ,
135
+ );
136
+
137
+ foreach ($ highlightFields as $ highlightField ) {
138
+ \assert (
139
+ isset ($ hit ['highlight ' ][$ highlightField ]['snippet ' ]),
140
+ 'Expected highlight field to be set. ' ,
141
+ );
142
+
143
+ $ document ['_formatted ' ][$ highlightField ] = $ hit ['highlight ' ][$ highlightField ]['snippet ' ];
144
+ }
145
+
146
+ yield $ document ;
116
147
}
117
148
}
118
149
0 commit comments