src/Service/CartService.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Menu;
  4. use App\Entity\Produit;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. class CartService {
  9.     private RequestStack $requestStack;
  10.     
  11.     private EntityManagerInterface $em;
  12.     public function __construct(RequestStack $requestStackEntityManagerInterface $em){
  13.         $this->requestStack =$requestStack;
  14.         $this->em=$em;
  15.     }
  16.     public function addToCart(string $id):void{
  17.         $cart=$this->getSession()->get('cart',[]);
  18.         if(!empty($cart[$id])){
  19.             $cart[$id]++;
  20.         }
  21.         else {
  22.             $cart[$id]=1;
  23.         }
  24.         $this->getSession()->set('cart',$cart);
  25.     }
  26.     public function decrease(string $id)
  27.     {
  28.         $cart=$this->getSession()->get('cart',[]);
  29.         if($cart[$id]>1){
  30.             $cart[$id]--;
  31.         }else{
  32.             unset($cart[$id]);
  33.         }
  34.         $this->getSession()->set('cart'$cart);
  35.     }
  36.     public function removeToCart(string $id)
  37.     {
  38.         $cart=$this->requestStack->getSession()->get('cart',[]);
  39.         unset($cart[$id]);
  40.         return $this->getSession()->set('cart'$cart);
  41.     }
  42.     public function removeCartAll()
  43.     {
  44.         return $this->getSession()->remove('cart');
  45.         
  46.     }
  47.     public function getTotal() : array
  48.     {
  49.         $cart $this->getSession()->get('cart');
  50.         $cartData = [];
  51.         foreach ($cart as $id => $quantite){
  52.             $produit $this->em->getRepository(Produit::class)->findOneBy(['id'=> $id]);
  53.             if(!$produit){
  54.                 //supprimer le produit puis sortir de la boucle
  55.             }
  56.             $cartData[]=[
  57.                 'produit'=>$produit,
  58.                 'quantite'=> $quantite
  59.             ];
  60.             
  61.         }
  62.         return $cartData;
  63.     }
  64.     private function getSession():SessionInterface
  65.     {
  66.         return $this->requestStack->getSession();
  67.     }
  68. }