Add search endpoint for sites (WIP)
This commit is contained in:
57
src/Service/SearchService.php
Normal file
57
src/Service/SearchService.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Repository\SiteRepository;
|
||||
use App\Enum\OpusEnum;
|
||||
use App\Enum\SitesCategoryEnum;
|
||||
use App\Exception\InvalidFilterException;
|
||||
|
||||
use function Symfony\Component\String\u;
|
||||
|
||||
final class SearchService
|
||||
{
|
||||
public function __construct(private readonly SiteRepository $siteRepository) {}
|
||||
|
||||
public function searchSites(array $rawFilters): array
|
||||
{
|
||||
$filters = $this->normalizeFilters($rawFilters);
|
||||
|
||||
// No results should be returned if no filter is valid
|
||||
if (empty($filters)) return [];
|
||||
|
||||
return array_map(
|
||||
fn(\App\Entity\Site $s) => $s->toSummary(),
|
||||
$this->siteRepository->findByFilters($filters)
|
||||
);
|
||||
}
|
||||
/**
|
||||
* @throws InvalidFilterException
|
||||
*/
|
||||
private function normalizeFilters(array $filters): array
|
||||
{
|
||||
$allowedFilters = ['text', 'technique', 'category'];
|
||||
$filters = array_intersect_key($filters, array_flip($allowedFilters));
|
||||
|
||||
$text = trim($filters['text'] ?? '');
|
||||
|
||||
if ($text !== '' && strlen($text) < 3) {
|
||||
throw new InvalidFilterException("Invalid text filter, length: " . strlen($filters['text']));
|
||||
}
|
||||
|
||||
// Prepare for LIKE query (useful?)
|
||||
$filters['text'] = $text !== '' ? '%' . u($text)->lower()->toUnicodeString() . '%' : '';
|
||||
|
||||
if (!empty($filters['technique']) && OpusEnum::tryFrom($filters['technique']) === null) {
|
||||
throw new InvalidFilterException("Invalid technique filter: " . $filters['technique']);
|
||||
}
|
||||
|
||||
if (!empty($filters['category']) && SitesCategoryEnum::tryFrom($filters['category']) === null) {
|
||||
throw new InvalidFilterException("Invalid category filter: " . $filters['category']);
|
||||
}
|
||||
|
||||
return $filters;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user