Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add possibility to define highlight start and end tag #70

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/Internal/Search/Highlighter/Highlighter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ public function __construct(
) {
}

public function highlight(string $text, TokenCollection $queryTokens): HighlightResult
{
public function highlight(
string $text,
TokenCollection $queryTokens,
string $startTag = '<em>',
string $endTag = '</em>',
): HighlightResult {
if ($text === '') {
return new HighlightResult($text, []);
}
Expand All @@ -43,9 +47,6 @@ public function highlight(string $text, TokenCollection $queryTokens): Highlight
return $a['start'] <=> $b['start'];
});

$startTag = '<em>';
$endTag = '</em>';

$pos = 0;
$highlightedText = '';
$spans = $this->extractSpansFromMatches($matches);
Expand Down
17 changes: 15 additions & 2 deletions src/Internal/Search/Searcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,9 @@ private function highlight(array &$hit, TokenCollection $tokenCollection): void
$this->searchParameters->getAttributesToHighlight()
;

$highlightStartTag = $this->searchParameters->getHighlightStartTag();
$highlightEndTag = $this->searchParameters->getHighlightEndTag();

foreach ($searchableAttributes as $attribute) {
// Do not include any attribute not required by the result (limited by attributesToRetrieve)
if (!isset($formatted[$attribute])) {
Expand All @@ -621,7 +624,12 @@ private function highlight(array &$hit, TokenCollection $tokenCollection): void
if (\is_array($formatted[$attribute])) {
foreach ($formatted[$attribute] as $key => $formattedEntry) {
$highlightResult = $this->engine->getHighlighter()
->highlight($formattedEntry, $tokenCollection);
->highlight(
$formattedEntry,
$tokenCollection,
$highlightStartTag,
$highlightEndTag
);

if (\in_array($attribute, $attributesToHighlight, true)) {
$formatted[$attribute][$key] = $highlightResult->getHighlightedText();
Expand All @@ -633,7 +641,12 @@ private function highlight(array &$hit, TokenCollection $tokenCollection): void
}
} else {
$highlightResult = $this->engine->getHighlighter()
->highlight((string) $formatted[$attribute], $tokenCollection);
->highlight(
(string) $formatted[$attribute],
$tokenCollection,
$highlightStartTag,
$highlightEndTag
);

if (\in_array($attribute, $attributesToHighlight, true)) {
$formatted[$attribute] = $highlightResult->getHighlightedText();
Expand Down
25 changes: 23 additions & 2 deletions src/SearchParameters.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ final class SearchParameters

private string $filter = '';

private string $highlightEndTag = '</em>';

private string $highlightStartTag = '<em>';

private int $hitsPerPage = 20;

private int $page = 1;
Expand Down Expand Up @@ -94,6 +98,8 @@ public function getHash(): string
$hash = [];

$hash[] = json_encode($this->getAttributesToHighlight());
$hash[] = json_encode($this->getHighlightStartTag());
$hash[] = json_encode($this->getHighlightEndTag());
$hash[] = json_encode($this->getAttributesToRetrieve());
$hash[] = json_encode($this->getAttributesToSearchOn());
$hash[] = json_encode($this->getFilter());
Expand All @@ -106,6 +112,16 @@ public function getHash(): string
return hash('sha256', implode(';', $hash));
}

public function getHighlightEndTag(): string
{
return $this->highlightEndTag;
}

public function getHighlightStartTag(): string
{
return $this->highlightStartTag;
}

public function getHitsPerPage(): int
{
return $this->hitsPerPage;
Expand Down Expand Up @@ -142,12 +158,17 @@ public function showRankingScore(): bool
/**
* @param array<string> $attributesToHighlight
*/
public function withAttributesToHighlight(array $attributesToHighlight): self
{
public function withAttributesToHighlight(
array $attributesToHighlight,
string $highlightStartTag = '<em>',
string $highlightEndTag = '</em>',
): self {
sort($attributesToHighlight);

$clone = clone $this;
$clone->attributesToHighlight = $attributesToHighlight;
$clone->highlightStartTag = $highlightStartTag;
$clone->highlightEndTag = $highlightEndTag;

return $clone;
}
Expand Down
44 changes: 41 additions & 3 deletions tests/Functional/SearchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,36 @@ public static function highlightingProvider(): \Generator
],
];

yield 'Highlight with custom start and end tag' => [
'assasin',
['title', 'overview'],
['title', 'overview'],
false,
[
'hits' => [
[
'id' => 24,
'title' => 'Kill Bill: Vol. 1',
'overview' => 'An assassin is shot by her ruthless employer, Bill, and other members of their assassination circle – but she lives to plot her vengeance.',
'genres' => ['Action', 'Crime'],
'_formatted' => [
'id' => 24,
'title' => 'Kill Bill: Vol. 1',
'overview' => 'An <mark>assassin</mark> is shot by her ruthless employer, Bill, and other members of their <mark>assassination</mark> circle – but she lives to plot her vengeance.',
'genres' => ['Action', 'Crime'],
],
],
],
'query' => 'assasin',
'hitsPerPage' => 20,
'page' => 1,
'totalPages' => 1,
'totalHits' => 1,
],
'<mark>',
'</mark>',
];

yield 'Highlight without typo' => [
'assassin',
['title', 'overview'],
Expand Down Expand Up @@ -1012,12 +1042,20 @@ public function testGeoSearch(): void
}

/**
* @param array<string> $searchableAttributes
* @param array<string> $attributesToHighlight
* @param array<mixed> $expectedResults
*/
#[DataProvider('highlightingProvider')]
public function testHighlighting(string $query, array $searchableAttributes, array $attributesToHighlight, bool $showMatchesPosition, array $expectedResults): void
{
public function testHighlighting(
string $query,
array $searchableAttributes,
array $attributesToHighlight,
bool $showMatchesPosition,
array $expectedResults,
string $highlightStartTag = '<em>',
string $highlightEndTag = '</em>',
): void {
$configuration = Configuration::create()
->withSearchableAttributes($searchableAttributes)
->withFilterableAttributes(['genres'])
Expand All @@ -1029,7 +1067,7 @@ public function testHighlighting(string $query, array $searchableAttributes, arr

$searchParameters = SearchParameters::create()
->withQuery($query)
->withAttributesToHighlight($attributesToHighlight)
->withAttributesToHighlight($attributesToHighlight, $highlightStartTag, $highlightEndTag)
->withShowMatchesPosition($showMatchesPosition)
->withAttributesToRetrieve(['id', 'title', 'overview', 'genres'])
->withSort(['title:asc'])
Expand Down
Loading