+
+ /**
+ * Insert search highlight token in provided field content based on a list of search result positions
+ *
+ * @param string $fieldContent
+ * @param array|null $positions List of of search results with 'start' and 'end' positions.
+ *
+ * @return string Updated $fieldContent.
+ */
+ protected function tokenizeSearchHighlightField(string $fieldContent, ?array $positions): string
+ {
+ if (empty($positions)) {
+ return $fieldContent;
+ }
+
+ $insertedTokens = 0;
+ $tokenLength = strlen(static::SEARCH_HIGHLIGHT_OPEN);
+ foreach ($positions as $position) {
+ $position = [
+ 'start' => $position['start'] + ($insertedTokens * $tokenLength),
+ 'end' => $position['end'] + ($insertedTokens * $tokenLength),
+ ];
+
+ $content = mb_substr($fieldContent, 0, $position['start']);
+ $content .= static::SEARCH_HIGHLIGHT_OPEN;
+ $content .= mb_substr($fieldContent, $position['start'], $position['end'] - $position['start']);
+ $content .= static::SEARCH_HIGHLIGHT_CLOSE;
+ $content .= mb_substr($fieldContent, $position['end']);
+
+ $fieldContent = $content;
+
+ $insertedTokens += 2;
+ }
+
+ return $fieldContent;
+ }
+
+ /**
+ * Replace search highlight tokens with HTML highlighted span.
+ *
+ * @param string $fieldContent
+ *
+ * @return string updated content.
+ */
+ protected function replaceTokens(string $fieldContent): string
+ {
+ return str_replace(
+ [static::SEARCH_HIGHLIGHT_OPEN, static::SEARCH_HIGHLIGHT_CLOSE],
+ ['<span class="search-highlight">', '</span>'],
+ $fieldContent
+ );
+ }
+
+ /**
+ * Apply replaceTokens to an array of content strings.
+ *
+ * @param string[] $fieldContents
+ *
+ * @return array
+ */
+ protected function replaceTokensArray(array $fieldContents): array
+ {
+ foreach ($fieldContents as &$entry) {
+ $entry = $this->replaceTokens($entry);
+ }
+
+ return $fieldContents;
+ }