Przeglądaj źródła

Correction typage contenu commentaires et notes

On supprime le stockage de la note moyenne

Oubli du filtre pour les notes
Sangfroid 3 miesięcy temu
rodzic
commit
876083a6e1

+ 33 - 0
migrations/Version20260711073337.php

@@ -0,0 +1,33 @@
+<?php
+
+declare(strict_types=1);
+
+namespace DoctrineMigrations;
+
+use Doctrine\DBAL\Schema\Schema;
+use Doctrine\Migrations\AbstractMigration;
+
+/**
+ * Auto-generated Migration: Please modify to your needs!
+ */
+final class Version20260711073337 extends AbstractMigration
+{
+    public function getDescription(): string
+    {
+        return '';
+    }
+
+    public function up(Schema $schema): void
+    {
+        // this up() migration is auto-generated, please modify it to your needs
+        $this->addSql('ALTER TABLE commentaire CHANGE contenu contenu LONGTEXT DEFAULT NULL');
+        $this->addSql('ALTER TABLE film CHANGE date_sortie date_sortie DATE DEFAULT NULL');
+    }
+
+    public function down(Schema $schema): void
+    {
+        // this down() migration is auto-generated, please modify it to your needs
+        $this->addSql('ALTER TABLE commentaire CHANGE contenu contenu TINYTEXT DEFAULT NULL');
+        $this->addSql('ALTER TABLE film CHANGE date_sortie date_sortie DATE DEFAULT NULL COMMENT \'(DC2Type:date_immutable)\'');
+    }
+}

+ 31 - 0
migrations/Version20260711075127.php

@@ -0,0 +1,31 @@
+<?php
+
+declare(strict_types=1);
+
+namespace DoctrineMigrations;
+
+use Doctrine\DBAL\Schema\Schema;
+use Doctrine\Migrations\AbstractMigration;
+
+/**
+ * Auto-generated Migration: Please modify to your needs!
+ */
+final class Version20260711075127 extends AbstractMigration
+{
+    public function getDescription(): string
+    {
+        return 'Supprime les colonnes note et nb_coms de la table film (remplacées par des getters calculés)';
+    }
+
+    public function up(Schema $schema): void
+    {
+        // this up() migration is auto-generated, please modify it to your needs
+        $this->addSql('ALTER TABLE film DROP note, DROP nb_coms');
+    }
+
+    public function down(Schema $schema): void
+    {
+        // this down() migration is auto-generated, please modify it to your needs
+        $this->addSql('ALTER TABLE film ADD note DOUBLE PRECISION DEFAULT NULL, ADD nb_coms INT DEFAULT NULL');
+    }
+}

+ 0 - 38
src/Command/UpdateCommentairesCommand.php

@@ -1,38 +0,0 @@
-<?php
-
-namespace App\Command;
-
-use App\Repository\FilmRepository;
-use App\Service\NoteMoyenne;
-use Symfony\Component\Console\Attribute\AsCommand;
-use Symfony\Component\Console\Command\Command;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Style\SymfonyStyle;
-
-#[AsCommand(
-    name: 'app:commentaires:update',
-    description: 'Update les notes et nb coms',
-)]
-class UpdateCommentairesCommand extends Command
-{
-
-    public function __construct(private NoteMoyenne $notesAndComs, private FilmRepository $repoFilm)
-    {
-        parent::__construct();
-    }
-
-    protected function execute(InputInterface $input, OutputInterface $output) :int
-    {
-        $io = new SymfonyStyle($input, $output);
-        $films = $this->repoFilm->findAll();
-        foreach ($films as $film)
-        {
-            $this->notesAndComs->calculerMoyenne($film);
-        }
-
-        $io->success('Tous les coms et toutes les notes sont mis à jour');
-        return COMMAND::SUCCESS;
-    }
-
-}

+ 3 - 1
src/Entity/Commentaire.php

@@ -5,6 +5,7 @@ namespace App\Entity;
 use App\Repository\CommentaireRepository;
 use Doctrine\DBAL\Types\Types;
 use Doctrine\ORM\Mapping as ORM;
+use Symfony\Component\Validator\Constraints as Assert;
 
 #[ORM\Table(name: "commentaire")]
 #[ORM\Entity(repositoryClass: CommentaireRepository::class)]
@@ -16,11 +17,12 @@ class Commentaire
 
     private ?int $id = null;
 
-    #[ORM\Column(name: "contenu", type: "text", length: 191, nullable: true)]
+    #[ORM\Column(name: "contenu", type: Types::TEXT, nullable: true)]
     
     private ?string $contenu = null;
 
     #[ORM\Column(name: "note", type: "integer", nullable: true)]
+    #[Assert\Range(min: 1, max: 5, notInRangeMessage: "La note doit être comprise entre {{ min }} et {{ max }}.")]
 
     private ?int $note = null;
 

+ 28 - 30
src/Entity/Film.php

@@ -31,12 +31,6 @@ class Film
     #[Assert\Url()]    
     private ?string $lien = null;
 
-    #[ORM\Column(name: "note", type: Types::FLOAT, nullable: true)]
-    private ?float $note = null;
-
-    #[ORM\Column(name: "nb_coms", type: Types::INTEGER, nullable: true)]
-    private ?int $nbComs = null;
-
     /*
     #[Assert\Valid()]
     #[ORM\OneToOne(targetEntity: MediaVideo::class, cascade: ["persist","remove"])]
@@ -257,30 +251,6 @@ class Film
         return $this;
     }
 
-    public function getNote(): ?float
-    {
-        return $this->note;
-    }
-
-    public function setNote(?float $note): self
-    {
-        $this->note = $note;
-
-        return $this;
-    }
-
-    public function getNbComs(): ?int
-    {
-        return $this->nbComs;
-    }
-
-    public function setNbComs(?int $nbComs): self
-    {
-        $this->nbComs = $nbComs;
-
-        return $this;
-    }
-
     public function getInformation(): ?string
     {
         return $this->information;
@@ -347,5 +317,33 @@ class Film
         return $this;
     }
 
+    /**
+     * Calcule et retourne la note moyenne du film à partir de ses commentaires.
+     * @return float|null La note moyenne (entre 1 et 5), ou null s'il n'y a pas de notes valides.
+     */
+    public function getAverageNote(): ?float
+    {
+        $notes = [];
+        foreach ($this->getCommentaires() as $commentaire) {
+            $note = $commentaire->getNote();
+            if ($note !== null && $note > 0) {
+                $notes[] = $note;
+            }
+        }
+
+        if (empty($notes)) {
+            return null;
+        }
+
+        return array_sum($notes) / count($notes);
+    }
+
+    /**
+     * Retourne le nombre total de commentaires.
+     */
+    public function getCommentCount(): int
+    {
+        return count($this->getCommentaires());
+    }
 
 }

+ 19 - 11
src/Repository/FilmRepository.php

@@ -124,10 +124,19 @@ class FilmRepository extends ServiceEntityRepository
         int $page = 1,
         array $filters = [],
     ): QueryBuilder {
-        $qb = $this->createQueryBuilder("f")->orderBy(
-            "f." . ($filters["sortBy"] ?? "dateSubmited"),
-            $filters["sortOrder"] ?? "DESC",
-        );
+        $qb = $this->createQueryBuilder("f");
+        
+        $sortBy = $filters["sortBy"] ?? "dateSubmited";
+        $sortOrder = $filters["sortOrder"] ?? "DESC";
+        
+        if ($sortBy === "note") {
+            $qb->orderBy(
+                "(SELECT AVG(c.note) FROM App\\Entity\\Commentaire c WHERE c.film = f AND c.note IS NOT NULL)",
+                $sortOrder
+            );
+        } else {
+            $qb->orderBy("f." . $sortBy, $sortOrder);
+        }
 
         if (!empty($filters["userWantToView"])) {
             $qb->leftJoin("f.usersWantToView", "wan")
@@ -141,19 +150,18 @@ class FilmRepository extends ServiceEntityRepository
             $qb->setMaxResults($limit);
         }
 
-        if (!empty($filters["note"])) {
-            $qb->andWhere("f.note >= :note")->setParameter(
-                "note",
-                $filters["note"],
-            );
-        }
-
         if (!empty($filters["username"])) {
             $qb->andWhere("f.authered = :authered")->setParameter(
                 "authered",
                 $filters["username"],
             );
         }
+
+        if (!empty($filters["note"])) {
+            $qb->andWhere(
+                "(SELECT AVG(c.note) FROM App\\Entity\\Commentaire c WHERE c.film = f AND c.note IS NOT NULL) >= :note"
+            )->setParameter("note", $filters["note"]);
+        }
         return $qb;
     }
 

+ 0 - 48
src/Service/NoteListener.php

@@ -1,48 +0,0 @@
-<?php
-
-namespace App\Service;
-
-use App\Entity\Commentaire;
-use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
-use Doctrine\ORM\Event\PostPersistEventArgs;
-use Doctrine\ORM\Event\PostRemoveEventArgs;
-use Doctrine\ORM\Event\PostUpdateEventArgs;
-use Doctrine\ORM\Events;
-use Doctrine\Persistence\Event\LifecycleEventArgs;
-
-#[AsDoctrineListener(event: Events::postPersist)]
-#[AsDoctrineListener(event: Events::postUpdate)]
-#[AsDoctrineListener(event: Events::postRemove)]
-class NoteListener
-{
-    public function __construct(protected NoteMoyenne $noteMoyenne) {}
-
-    public function postPersist(PostPersistEventArgs $args): void
-    {
-        $this->calculer($args);
-    }
-
-    public function postUpdate(PostUpdateEventArgs $args): void
-    {
-        $this->calculer($args);
-    }
-
-    public function postRemove(PostRemoveEventArgs $args): void
-    {
-        $this->calculer($args);
-    }
-
-    /**
-     * @param LifecycleEventArgs $args
-     */
-    private function calculer(LifecycleEventArgs $args): void
-    {
-        $entity = $args->getObject();
-
-        if (!$entity instanceof Commentaire) {
-            return;
-        }
-
-        $this->noteMoyenne->calculerMoyenne($entity->getFilm());
-    }
-}

+ 0 - 50
src/Service/NoteMoyenne.php

@@ -1,50 +0,0 @@
-<?php
-
-namespace App\Service;
-
-use App\Entity\Film;
-use Doctrine\ORM\EntityManagerInterface;
-use Exception;
-
-/**
- * Calculer moyenne pour un film
- */
-class NoteMoyenne {
-
-    public function __construct(protected EntityManagerInterface $em)
-    {
-    }
-
-    public function calculerMoyenne (Film $film): void
-    {
-        $commentaires = $film->getCommentaires();
-
-        $total = 0;
-        $nb = 0;
-
-        foreach ($commentaires as $commentaire) {
-            if ($commentaire->getNote() > 0 && $commentaire->getNote() != null)
-                $nb++;
-            $total += $commentaire->getNote();
-        }
-
-        $note = 0;
-
-        if ($nb > 0) {
-            $note = $total / $nb;
-        }
-        if ($note == 0)
-            $note = null;
-
-        $film->setNote($note);
-        $film->setNbComs(count($commentaires));
-        try {
-            $this->em->flush();
-        } 
-        
-        catch (Exception $e)
-        {
-            //dump($e);
-        }
-    }
-}

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

@@ -83,7 +83,7 @@
 					{% if film.new %}<span class="badge bg-secondary">New</span>{% endif %}
 					{% if estEnSalle(film.dateSortie) %}<span class="badge text-bg-success">En salle</span>{% endif %}
 					{% if bientotEnSalle(film.dateSortie) %}<span class="badge text-bg-info">Bientot</span>{% endif %}
-					{% if film.nbComs %}<span class="badge text-bg-warning rounded-pill" data-bs-toggle="tooltip" title="{{ film.nbComs }} commentaire(s)">{{ film.nbComs }}</span>{% endif %}
+					{% if film.commentCount %}<span class="badge text-bg-warning rounded-pill" data-bs-toggle="tooltip" title="{{ film.commentCount }} commentaire(s)">{{ film.commentCount }}</span>{% endif %}
 
 				</td>
 				<td>
@@ -97,7 +97,7 @@
 					{% endfor %}
 				</td>
 				<td>
-					{% if film.note > 0 %}
+					{% if film.averageNote > 0 %}
 						<input class="rating"
 							data-disabled="true"
 							data-show-clear="false"
@@ -108,7 +108,7 @@
 							max=5
 							data-step=0.5
 							data-size="xs"
-							value="{{ film.note }}">
+							value="{{ film.averageNote }}">
 					{% endif %}
 				</td>
 				<td>{% if film.annee is not null %}{{ film.annee | date('Y') }}{% endif %}</td>

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

@@ -119,11 +119,11 @@
 							max=5
 							data-step=0.5
 							data-size="xs"
-							value="{{ film.note }}">
+							value="{{ film.averageNote }}">
 					</div>
 					<div class="me-3">
-						{% if film.nbComs %}
-							<a href="{{ path('videotheque_voirfilm', {'id': film.id}) }}#coms"><span class="badge text-bg-warning">{{ film.nbComs }} commentaire{% if film.nbComs > 1 %}s{% endif %}</span></a>
+						{% if film.commentCount %}
+							<a href="{{ path('videotheque_voirfilm', {'id': film.id}) }}#coms"><span class="badge text-bg-warning">{{ film.commentCount }} commentaire{% if film.commentCount > 1 %}s{% endif %}</span></a>
 						{% endif %}
 					</div>
 					<div class="">

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

@@ -35,7 +35,7 @@
     {% endif %}
     {{ film.titre }}
     
-    {% if film.note > 0 %}
+    {% if film.averageNote > 0 %}
         <p>
             <input class="rating"
                data-disabled="true"
@@ -47,7 +47,7 @@
                style="display:none;"
                data-step=0.5
                data-size="xs"
-               value="{{ film.note }}">
+               value="{{ film.averageNote }}">
         </p>
     {% endif %}
 {% endblock %}