Skip to content

Commit b3a5bf4

Browse files
committed
Improved highlighting
1 parent 437fad2 commit b3a5bf4

File tree

1 file changed

+67
-3
lines changed

1 file changed

+67
-3
lines changed

src/Eloquent/Model.php

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@
1212
use PDPhilip\Elasticsearch\Query\Builder as QueryBuilder;
1313
use RuntimeException;
1414

15-
15+
/**
16+
* @property object $searchHighlights
17+
* @property array $searchHighlightsAsArray
18+
* @property object $withHighlights
19+
*/
1620
abstract class Model extends BaseModel
1721
{
1822
use HybridRelations, ModelDocs;
@@ -139,9 +143,41 @@ public function getMeta()
139143
return (object)$this->_meta;
140144
}
141145

142-
public function getHighlights()
146+
public function getSearchHighlightsAttribute()
147+
{
148+
if (!empty($this->_meta['highlights'])) {
149+
$data = [];
150+
$this->_mergeFlatKeysIntoNestedArray($data, $this->_meta['highlights']);
151+
152+
return (object)$data;
153+
}
154+
155+
return null;
156+
}
157+
158+
public function getSearchHighlightsAsArrayAttribute()
143159
{
144-
return $this->_meta['highlights'] ?? [];
160+
if (!empty($this->_meta['highlights'])) {
161+
return $this->_meta['highlights'];
162+
}
163+
164+
return [];
165+
}
166+
167+
public function getWithHighlightsAttribute()
168+
{
169+
$data = $this->attributes;
170+
$mutators = array_values(array_diff($this->getMutatedAttributes(), ['id', 'search_highlights', 'search_highlights_as_array', 'with_highlights']));
171+
if ($mutators) {
172+
foreach ($mutators as $mutator) {
173+
$data[$mutator] = $this->{$mutator};
174+
}
175+
}
176+
if (!empty($this->_meta['highlights'])) {
177+
$this->_mergeFlatKeysIntoNestedArray($data, $this->_meta['highlights']);
178+
}
179+
180+
return (object)$data;
145181
}
146182

147183
/**
@@ -414,4 +450,32 @@ public function saveWithoutRefresh(array $options = [])
414450
return $saved;
415451
}
416452

453+
454+
//----------------------------------------------------------------------
455+
// Helpers
456+
//----------------------------------------------------------------------
457+
458+
protected function _mergeFlatKeysIntoNestedArray(&$data, $attrs)
459+
{
460+
foreach ($attrs as $key => $value) {
461+
if ($value) {
462+
$value = implode('......', $value);
463+
$parts = explode('.', $key);
464+
$current = &$data;
465+
466+
foreach ($parts as $partIndex => $part) {
467+
if ($partIndex === count($parts) - 1) {
468+
$current[$part] = $value;
469+
} else {
470+
if (!isset($current[$part]) || !is_array($current[$part])) {
471+
$current[$part] = [];
472+
}
473+
$current = &$current[$part];
474+
}
475+
}
476+
}
477+
478+
}
479+
}
480+
417481
}

0 commit comments

Comments
 (0)