Files
3dealer/app/Support/SearchHighlight.php
T

75 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Support;
use Illuminate\Support\HtmlString;
use Normalizer;
/**
* Underlines the words of a product name that a search query matched, for
* the live search dropdown: every word starting with one of the query's
* words ("click" → "Edamame _Clicker_"), ignoring case and accents the way
* Meilisearch does ("παπ" → "_Παπάκι_"). Typo matches aren't marked — the
* name is shown as is.
*/
final class SearchHighlight
{
public static function name(string $name, string $query, string $class = 'underline underline-offset-4'): HtmlString
{
$terms = array_values(array_filter(preg_split('/[^\p{L}\p{N}]+/u', self::fold($query)) ?: []));
$chars = mb_str_split($name);
if ($terms === [] || $chars === []) {
return new HtmlString(e($name));
}
// One folded character per original one, so positions line up.
$folded = array_map(self::fold(...), $chars);
$html = '';
$i = 0;
$count = count($chars);
while ($i < $count) {
if (! self::isWordChar($chars[$i])) {
$html .= e($chars[$i++]);
continue;
}
$end = $i;
while ($end < $count && self::isWordChar($chars[$end])) {
$end++;
}
$word = implode('', array_slice($chars, $i, $end - $i));
$foldedWord = implode('', array_slice($folded, $i, $end - $i));
$matched = collect($terms)->contains(fn (string $term) => str_starts_with($foldedWord, $term));
$html .= $matched ? '<span class="'.e($class).'">'.e($word).'</span>' : e($word);
$i = $end;
}
return new HtmlString($html);
}
/**
* Lower case, without accents; Greek final sigma as σ.
*/
private static function fold(string $text): string
{
if (class_exists(Normalizer::class)) {
$text = preg_replace('/\p{Mn}+/u', '', Normalizer::normalize($text, Normalizer::FORM_D) ?: $text);
}
return strtr(mb_strtolower($text), [
'ά' => 'α', 'έ' => 'ε', 'ή' => 'η', 'ί' => 'ι', 'ό' => 'ο', 'ύ' => 'υ', 'ώ' => 'ω',
'ϊ' => 'ι', 'ϋ' => 'υ', 'ΐ' => 'ι', 'ΰ' => 'υ', 'ς' => 'σ',
]);
}
private static function isWordChar(string $char): bool
{
return (bool) preg_match('/[\p{L}\p{N}]/u', $char);
}
}