<?php
namespace App\Controller\api;
use App\Model\GlobalSearch\SearchCriteria;
use App\Service\GlobalSearch\GlobalSearchService;
use Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/api/immo/v2/search", name="global_search_")
*/
class GlobalSearchController
{
/**
* @Route("", name="index", methods={"GET"})
*/
public function index(
Request $request,
GlobalSearchService $globalSearchService
): JsonResponse {
$q = trim((string) $request->query->get('q', ''));
$categories = $request->query->all('categories');
if ($q === '') {
return new JsonResponse([
'success' => false,
'code' => Response::HTTP_BAD_REQUEST,
'message' => 'Parameter "q" is required and cannot be empty.',
], Response::HTTP_BAD_REQUEST);
}
$criteria = new SearchCriteria($q, $categories);
$results = $globalSearchService->search($criteria);
$formattedData = [];
foreach ($results as $category => $result) {
$formattedData[$category] = [
'items' => $result->getItems(),
];
}
return new JsonResponse([
'success' => true,
'code' => Response::HTTP_OK,
'data' => $formattedData,
]);
}
/**
* @Route("/{category}", name="category_details", methods={"GET"})
*/
public function categoryDetails(
string $category,
Request $request,
GlobalSearchService $globalSearchService
): JsonResponse {
$q = trim((string) $request->query->get('q', ''));
$page = $request->query->getInt('page', 1);
$limit = $request->query->getInt('itemsPerPage', 9);
if ($q === '') {
return new JsonResponse([
'success' => false,
'code' => Response::HTTP_BAD_REQUEST,
'message' => 'Parameter "q" is required and cannot be empty.',
], Response::HTTP_BAD_REQUEST);
}
try {
$criteria = new SearchCriteria($q, [$category], $page, $limit);
$result = $globalSearchService->searchByCategory($category, $criteria);
$totalItems = $result->getTotal();
$totalPages = (int) ceil($totalItems / $limit);
return new JsonResponse([
'data' => $result->getItems(),
'message' => 'OK',
'code' => Response::HTTP_OK,
'success' => true,
'total' => $totalItems,
'last_page' => $totalPages,
'current_page' => $page,
]);
} catch (Exception $e) {
return new JsonResponse([
'success' => false,
'code' => Response::HTTP_NOT_FOUND,
'message' => $e->getMessage(),
], Response::HTTP_NOT_FOUND);
}
}
}