Преглед на файлове

Filtres fonctionnels mais refactorisation à faire

Sangfroid преди 9 месеца
родител
ревизия
a6d8554588

+ 37 - 15
src/Controller/VideothequeController.php

@@ -10,6 +10,7 @@ use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\Routing\Annotation\Route;
 use Symfony\Component\HttpFoundation\Request;
 use App\Entity\Film;
+use App\Entity\Genre;
 use App\Form\CommentaireType;
 use App\Form\FilmType;
 use App\Form\FiltersType;
@@ -19,7 +20,6 @@ use App\Repository\GenreRepository;
 use App\Repository\RealisateurRepository;
 use App\Service\CommentaireManager;
 use App\Service\FilmManager;
-use App\Service\FiltersService;
 use App\Service\OptionsManager;
 use App\Service\TmdbApiService;
 use Symfony\Bundle\SecurityBundle\Security;
@@ -30,22 +30,20 @@ use Symfony\Component\Security\Http\Attribute\IsGranted;
 class VideothequeController extends AbstractController
 {
 	#[Route("/", name: "videotheque_liste")]
-	public function listeAction(Request $request, FilmRepository $repo, OptionsManager $options, FiltersService $filtersService): Response
+	public function listeAction(Request $request, FilmRepository $filmRepository, OptionsManager $options): Response
 	{
-        $listeFilms = $repo->findTous();
+        $session = $request->getSession();
 
-        $filterDto = new FiltersDTO();
+        $filterDto = $session->get('filters', new FiltersDTO());
         $filtersForm = $this->createForm(FiltersType::class, $filterDto);
 
         $filtersForm->handleRequest($request);
 
         if ($filtersForm->isSubmitted() && $filtersForm->isValid()) {
-            // Récupérer les données de tri et de filtre
-            $filters = $filtersForm->getData();
-    
-            // Appliquer les filtres et les tris
-            $listeFilms = $filtersService->applyFiltersAndSort($listeFilms, $filters);
+            $session->set('filters', $filterDto);
         }
+        $filters = $filtersForm->getData();
+        $listeFilms = $filmRepository->findTous($filters->toArray());
 
 		return $this->render('videotheque/liste_'.$options->vue().'.html.twig', array(
             'listeFilms'	=>	$listeFilms,
@@ -66,24 +64,48 @@ class VideothequeController extends AbstractController
     }
 
     #[Route("/liste-by/{id}", name: "videotheque_listepargenre")]
-	public function  listeParGenreAction(\App\Entity\Genre $genre, FilmRepository $repo, OptionsManager $options): Response
+	public function  listeParGenreAction(Request $request, Genre $genre, FilmRepository $repo, OptionsManager $options): Response
     {
-        $films = $repo->findFilmWithGenre(array($genre->getName()));
+        $session = $request->getSession();
+
+        $filterDto = $session->get('filters', new FiltersDTO());
+        $filtersForm = $this->createForm(FiltersType::class, $filterDto);
+
+        $filtersForm->handleRequest($request);
+
+        if ($filtersForm->isSubmitted() && $filtersForm->isValid()) {
+            $session->set('filters', $filterDto);
+        }
+        $filters = $filtersForm->getData();
+        $films = $repo->findFilmWithGenre([$genre->getName()], $filters->toArray());
 
         return $this->render('videotheque/liste_'.$options->vue().'.html.twig', array(
             'listeFilms'    => $films,
-            'titre'         => 'Films par catégorie : '.$genre->getName()
+            'titre'         => 'Films par catégorie : '.$genre->getName(),
+            'filtersForm'   => $filtersForm
         ));
     }
 
     #[Route("/liste-by_real/{id}", name: "videotheque_listeparreal")]
-    public function  listeParRealisateurAction(Realisateur $realisateur, FilmRepository $repo, OptionsManager $options): Response
+    public function  listeParRealisateurAction(Request $request, Realisateur $realisateur, FilmRepository $repo, OptionsManager $options): Response
     {
-        $films = $repo->findFilmWithReal(array($realisateur->getNomComplet()));
+        $session = $request->getSession();
+
+        $filterDto = $session->get('filters', new FiltersDTO());
+        $filtersForm = $this->createForm(FiltersType::class, $filterDto);
+
+        $filtersForm->handleRequest($request);
+
+        if ($filtersForm->isSubmitted() && $filtersForm->isValid()) {
+            $session->set('filters', $filterDto);
+        }
+        $filters = $filtersForm->getData();
+        $films = $repo->findFilmWithReal([$realisateur->getNomComplet()], $filters->toArray());
 
         return $this->render('videotheque/liste_'.$options->vue().'.html.twig', array(
             'listeFilms'    => $films,
-            'titre'         => 'Films par réalisateur : '.$realisateur->getNomComplet()
+            'titre'         => 'Films par réalisateur : '.$realisateur->getNomComplet(),
+            'filtersForm'   => $filtersForm
         ));
     }
 

+ 18 - 4
src/Controller/VideothequePersonnelleController.php

@@ -2,8 +2,11 @@
 
 namespace App\Controller;
 
+use App\Dto\FiltersDTO;
+use App\Form\FiltersType;
 use App\Repository\FilmRepository;
 use App\Service\FilmManager;
+use App\Service\FiltersService;
 use App\Service\OptionsManager;
 use Doctrine\ORM\EntityManagerInterface;
 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -15,13 +18,24 @@ use Symfony\Component\HttpFoundation\Response;
 class VideothequePersonnelleController extends AbstractController
 {
 	#[Route("/maliste", name:"videothequepersonnelle_maliste")]
-	public function maListeAction (Request $request, FilmRepository $repo, OptionsManager $options): Response
+	public function maListeAction (Request $request, OptionsManager $options, FilmRepository $filmRepository): Response
     {
-        $films = $repo->findTousFavoritesByUser($this->getUser());
+        $session = $request->getSession();
 
+        $filterDto = $session->get('filters', new FiltersDTO());
+        $filtersForm = $this->createForm(FiltersType::class, $filterDto);
+
+        $filtersForm->handleRequest($request);
+
+        if ($filtersForm->isSubmitted() && $filtersForm->isValid()) {
+            $session->set('filters', $filterDto);
+        }
+        $filters = $filtersForm->getData();
+        $listeFilms = $filmRepository->findTousFavoritesByUser($this->getUser(), $filters->toArray());
         return $this->render('videotheque/liste_'.$options->vue().'.html.twig', array(
-            'listeFilms'    =>  $films,
-            'titre'         =>  'Ma liste de films à voir'
+            'listeFilms'    =>  $listeFilms,
+            'titre'         =>  'Ma liste de films à voir',
+            'filtersForm'   => $filtersForm->createView()
         ));
     }
 

+ 13 - 3
src/Dto/FiltersDTO.php

@@ -12,10 +12,10 @@ class FiltersDTO
         #[Assert\LessThanOrEqual(100)]
         public int $nbResults = 25,
 
+        public ?string $userName = null,
+        
         #[Assert\NotBlank()]
-        public string $userName = '',
-
-        public string $sortBy = '',
+        public string $sortBy = 'dateSubmited',
 
         #[Assert\Choice(['ASC', 'DESC'])]
         public string $sortOrder = 'DESC'
@@ -23,4 +23,14 @@ class FiltersDTO
     {
         
     }
+
+    public function toArray(): array
+    {
+        return [
+            'limit'     => $this->nbResults,
+            'username'  => $this->userName,
+            'sortBy'    => $this->sortBy,
+            'sortOrder' => $this->sortOrder
+        ];
+    }
 }

+ 26 - 5
src/Form/FiltersType.php

@@ -4,7 +4,7 @@ namespace App\Form;
 
 use App\Dto\FiltersDTO;
 use Symfony\Component\Form\AbstractType;
-use Symfony\Component\Form\Extension\Core\Type\IntegerType;
+use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
 use Symfony\Component\Form\FormBuilderInterface;
 use Symfony\Component\OptionsResolver\OptionsResolver;
 
@@ -13,10 +13,31 @@ class FiltersType extends AbstractType
     public function buildForm(FormBuilderInterface $builder, array $options): void
     {
         $builder
-            ->add('nbResults', IntegerType::class)
-            ->add('userName')
-            ->add('sortBy')
-            ->add('sortOrder')
+            ->add('nbResults', ChoiceType::class, [
+                'choices' => [
+                    '10' => 10,
+                    '25' => 25,
+                    '50' => 50,
+                    '100' => 100
+                ]
+            ])
+            ->add('userName', null, [
+                'required' => false
+            ])
+            ->add('sortBy', ChoiceType::class, [
+                'choices' => [
+                    'Date de soumission' => 'dateSubmited',
+                    'Titre' => 'titre',
+                    'Année' => 'annee',
+                    'Note' => 'note'
+                ]
+            ])
+            ->add('sortOrder',ChoiceType::class, [
+                'choices' => [
+                    'ASC' => 'ASC',
+                    'DESC' => 'DESC'
+                ]
+            ])
         ;
     }
 

+ 21 - 33
src/Repository/FilmRepository.php

@@ -4,6 +4,8 @@ namespace App\Repository;
 
 use App\Entity\Film;
 use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
+use Doctrine\ORM\QueryBuilder;
+use Doctrine\ORM\Tools\Pagination\Paginator;
 use Doctrine\Persistence\ManagerRegistry;
 
 /**
@@ -31,31 +33,27 @@ class FilmRepository extends ServiceEntityRepository
         return $query->getSingleResult();
     }
 
-    public function findFilmWithGenre(array $genreNames) : array
+    public function findFilmWithGenre(array $genreNames, array $filters = []) : Paginator
     {
-        $qb = $this->createQueryBuilder('f');
+        $qb = $this->queryFilter($filters);
         $qb
             ->innerJoin('f.genres', 'g')
             ->addSelect('f');
 
         $qb->where($qb->expr()->in('g.name', $genreNames));
 
-        return $qb
-            ->getQuery()
-            ->getResult();
+        return new Paginator($qb->getQuery());
     }
 
-    public function findFilmWithReal(array $realisateursnames): array
+    public function findFilmWithReal(array $realisateursnames, array $filters = []): Paginator
     {
-        $qb = $this->createQueryBuilder('f');
+        $qb = $this->queryFilter($filters);
         $qb
             ->leftJoin('f.realisateurs', 'rea')
             ->addSelect('f')
             ->where($qb->expr()->in('rea.nomComplet', $realisateursnames));
 
-        return $qb
-            ->getQuery()
-            ->getResult();
+        return new Paginator($qb->getQuery());
     }
 
     public function findFilmWithRealLike($query): array
@@ -87,35 +85,27 @@ class FilmRepository extends ServiceEntityRepository
             ->getResult();
     }
 
-
-
-    public function findTousDesc(): array
+    public function queryFilter(array $filters = []): QueryBuilder
     {
-        $qb = $this->createQueryBuilder('f');
-        $qb
-            ->select('f')
-            ->orderBy('f.dateSubmited', 'DESC');
-
-        return $qb
-            ->getQuery()
-            ->getResult();
+        return $this->createQueryBuilder('f')
+            ->orderBy('f.'.($filters['sortBy'] ?? 'dateSubmited'), $filters['sortOrder'] ?? 'DESC')
+            ->setMaxResults((int)($filters['limit'] ?? 100))
+        ;
     }
 
-    public function findTous (): array
+    public function findTous (array $filters = []): ?Paginator
     {
-        $qb = $this->createQueryBuilder('f')
+        $qb = $this->queryFilter($filters)
             ->leftJoin('f.authered', 'aut')->addSelect('aut')
             ->leftJoin('f.genres', 'gen')->addSelect('gen')
             ->leftJoin('f.realisateurs', 'rea')->addSelect('rea')
-            ->orderBy('f.dateSubmited', 'DESC');
-        return $qb
-            ->getQuery()
-            ->getResult();
+        ;
+        return new Paginator($qb->getQuery());
     }
 
-    public function findTousFavoritesByUser($user): array
+    public function findTousFavoritesByUser($user, array $filters = []): ?Paginator
     {
-        $qb = $this->createQueryBuilder('f');
+        $qb = $this->queryFilter($filters);
         $qb
             ->leftJoin('f.authered', 'aut')->addSelect('aut')
             ->leftJoin('f.genres', 'gen')->addSelect('gen')
@@ -123,10 +113,8 @@ class FilmRepository extends ServiceEntityRepository
             ->leftJoin('f.usersWantToView', 'wan')
             ->where($qb->expr()->in('wan', ':user'))
             ->setParameter('user', $user)
-            ->orderBy('f.dateSubmited', 'DESC');
-        return $qb
-            ->getQuery()
-            ->getResult();
+        ;
+        return new Paginator($qb->getQuery());
     }
 
     public function findProchaines(): array

+ 0 - 14
src/Service/FiltersService.php

@@ -1,14 +0,0 @@
-<?php
-
-namespace App\Service;
-
-use App\Dto\FiltersDTO;
-
-class FiltersService
-{
-    public function applyFiltersAndSort(?array $data, FiltersDTO $filters)
-    {
-        $filteredData = $data;
-        return $filteredData;
-    }
-}

+ 6 - 4
templates/videotheque/_filters_form.html.twig

@@ -1,6 +1,8 @@
-{{ form_start(filtersForm) }}
+{% if filtersForm is defined %}
+    {{ form_start(filtersForm) }}
 
-{{ form_rest(filtersForm)}}
-<button class="btn btn-primary mb-3" type="submit">Filtrer</button>
+    {{ form_rest(filtersForm)}}
+    <button class="btn btn-primary mb-3" type="submit">Filtrer</button>
 
-{{ form_end(filtersForm) }}
+    {{ form_end(filtersForm) }}
+{% endif %}

+ 3 - 1
templates/videotheque/_liste_header.html.twig

@@ -20,4 +20,6 @@
         data-size="sm"
         value="0">
     </p>
-</div>
+</div>
+
+{{ include ('videotheque/_filters_form.html.twig') }}

+ 1 - 1
templates/videotheque/liste_tableaux.html.twig

@@ -111,7 +111,7 @@
 							value="{{ film.note }}">
 					{% endif %}
 				</td>
-				<td>{{ film.annee | date('Y') }}</td>
+				<td>{% if film.annee is not null %}{{ film.annee | date('Y') }}{% endif %}</td>
 				<td>
 					{% if film.dateSortie %}{{ film.dateSortie | date('d/m/y')}}{% endif %}
 				</td>

+ 2 - 2
templates/videotheque/liste_vignettes.html.twig

@@ -12,8 +12,6 @@
 
 	{{ include ('videotheque/_liste_header.html.twig') }}
 
-	{{ include ('videotheque/_filters_form.html.twig') }}
-
 	<section id="tableFilms">
 		
 		{% for film in listeFilms %}
@@ -69,10 +67,12 @@
 			<div class="card-body collapse" id="collapse-id-{{ film.id }}" data-collapser-target="collapse">
 				<table class="table">
 					<tbody>
+						{% if film.annee %}
 						<tr>
 							<th style="width: 9em;">Année</th>
 							<td>{{ film.annee | date('Y') }}</td>
 						<tr>
+						{% endif %}
 						<tr>
 							<th>Réalisateur(s)</th>
 							<td>

+ 2 - 0
templates/videotheque/voirfilm.html.twig

@@ -81,8 +81,10 @@
                 </div>
                 <div class="card-body">
                     <dl class="row">
+                        {% if film.annee %}
                         <dt class="col-4">Année</dt>
                         <dd class="col-8">{{ film.annee | date('Y') }}</dd>
+                        {% endif %}
                         <dt class="col-4">Réalisateur(s)</dt>
                         <dd class="col-8">
                         {% for realisateur in film.realisateurs %}