NoteMoyenne.php 1001 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace AppBundle\Service;
  3. use AppBundle\Entity\Film;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. /**
  6. * Calculer moyenne pour un film
  7. */
  8. class NoteMoyenne {
  9. private $em;
  10. public function __construct(EntityManagerInterface $em)
  11. {
  12. $this->em = $em;
  13. }
  14. public function calculerMoyenne (Film $film)
  15. {
  16. $commentaires = $this->em
  17. ->getRepository('AppBundle:Commentaire')
  18. ->findBy(array('film' => $film));
  19. $notes[] = array();
  20. $total = 0;
  21. $nb = 0;
  22. foreach ($commentaires as $commentaire) {
  23. if ($commentaire->getNote() > 0 && $commentaire->getNote() != null)
  24. $nb++;
  25. $total += $commentaire->getNote();
  26. }
  27. $note = 0;
  28. if ($nb > 0) {
  29. $note = $total / $nb;
  30. }
  31. if ($note == 0)
  32. $note = null;
  33. $film->setNote($note);
  34. $film->setNbComs(count($commentaires));
  35. $this->em->flush();
  36. }
  37. }