src/Controller/HomeController.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Repository\AnnoncesRepository;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. class HomeController extends AbstractController
  10. {
  11.     /**
  12.      * @Route("/", name="home")
  13.      * @param AnnoncesRepository $annoncesRepository
  14.      * @return Response
  15.      */
  16.     public function index(AnnoncesRepository $annoncesRepository)
  17.     {
  18.         $content "Binvenue sur notre site d'annonces des concours !";
  19.         return $this->render('home/index.html.twig', [
  20.             'content' =>$content,
  21.             'ads' => $annoncesRepository->findAll(),
  22.         ]);
  23.     }
  24.     /**
  25.  * @Route("/search", name="search_annonces", methods={"GET"})
  26.  */
  27. public function search(Request $requestAnnoncesRepository $annoncesRepository): JsonResponse
  28. {
  29.     // Récupération du terme de recherche depuis l'URL (ex: /search?query=ma+recherche)
  30.     $query $request->query->get('query');
  31.     // On utilise une méthode du repository (voir la suite) pour chercher dans le titre, le contenu ou le nom de la ville
  32.     $annonces $annoncesRepository->searchByQuery($query);
  33.     // Construction du tableau de résultats
  34.     $results = [];
  35.     // Exemple dans HomeController.php
  36.     foreach ($annonces as $annonce) {
  37.         $results[] = [
  38.             'id'      => $annonce->getId(),
  39.             'title'   => $annonce->getTitle(),
  40.             'content' => substr($annonce->getContent(), 0100),
  41.             'ville'   => $annonce->getVille() ? $annonce->getVille()->getName() : '',
  42.             'slug'    => $annonce->getSlug(),
  43.             'image'   => $annonce->getImage(), // Ajout de la propriété image
  44.             'date'    => $annonce->getCreatedAt()->format('d/m/Y'),
  45.             'author'  => $annonce->getAuthor()->getUsername(),
  46.             'departement' => $annonce->getVille()->getDepartements()->getName(),
  47.             'region' => $annonce->getVille()->getDepartements()->getRegions()->getName()
  48.         ];
  49.     }
  50.     return new JsonResponse(['annonces' => $results]);
  51. }
  52. }