Files

71 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Http\Controllers;
use App\Catalog\ProductCard;
use App\Catalog\ProductListing;
use App\Catalog\ProductListingPage;
use Modules\Core\Catalog\Services\ProductSearchService;
class SearchController extends Controller
{
/** Live search answers from this many characters on. */
public const LIVE_MIN_CHARS = 3;
/** How many products the live search dropdown lists. */
private const LIVE_LIMIT = 6;
public function __construct(
private readonly ProductListingPage $listingPage,
private readonly ProductSearchService $search,
) {}
public function show(string $locale)
{
$query = trim((string) request()->query('q', ''));
// The search overlay's live results: the same endpoint, asked for by
// its <turbo-frame id="search-suggestions"> as the shopper types.
if (request()->header('Turbo-Frame') === 'search-suggestions') {
return $this->suggestions($query);
}
if ($query === '') {
return redirect()->route('products');
}
$listing = ProductListing::fromRequest(request());
$data = $this->listingPage->build(
$listing,
fn (array $overrides) => route('search', ['q' => $query] + $overrides),
collectionId: null,
query: $query,
);
return view('search.index', [...$data, 'query' => $query]);
}
/**
* The first few matches and how many there are in all — the dropdown
* under the search overlay. Empty below LIVE_MIN_CHARS characters.
*/
private function suggestions(string $query)
{
$products = collect();
$total = 0;
if (mb_strlen($query) >= self::LIVE_MIN_CHARS) {
$result = $this->search->search($query, perPage: self::LIVE_LIMIT);
$products = collect($result->products->items())->map(ProductCard::fromIndexed(...));
$total = $result->products->total();
}
return view('search.suggestions', [
'query' => $query,
'products' => $products,
'total' => $total,
'searched' => mb_strlen($query) >= self::LIVE_MIN_CHARS,
]);
}
2026-09-04 13:19:24 +03:00
}