NoteMoyenne.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Film;
  4. use Doctrine\Common\Util\Debug;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Exception;
  7. /**
  8. * Calculer moyenne pour un film
  9. */
  10. class NoteMoyenne {
  11. private $em;
  12. public function __construct(EntityManagerInterface $em)
  13. {
  14. $this->em = $em;
  15. }
  16. public function calculerMoyenne (Film $film)
  17. {
  18. $commentaires = $film->getCommentaires();
  19. $total = 0;
  20. $nb = 0;
  21. foreach ($commentaires as $commentaire) {
  22. if ($commentaire->getNote() > 0 && $commentaire->getNote() != null)
  23. $nb++;
  24. $total += $commentaire->getNote();
  25. }
  26. $note = 0;
  27. if ($nb > 0) {
  28. $note = $total / $nb;
  29. }
  30. if ($note == 0)
  31. $note = null;
  32. $film->setNote($note);
  33. $film->setNbComs(count($commentaires));
  34. try {
  35. $this->em->flush();
  36. }
  37. catch (Exception $e)
  38. {
  39. dump($e);
  40. }
  41. }
  42. }