src/Twig/CartExtension.php line 39

  1. <?php
  2. namespace App\Twig;
  3. use App\Entity\Product;
  4. use App\Service\Cart\CartService;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Twig\Extension\AbstractExtension;
  8. use Twig\TwigFunction;
  9. class CartExtension extends AbstractExtension
  10. {
  11.     private RequestStack $session;
  12.     private EntityManagerInterface $entityManager;
  13.     private CartService $cartService;
  14.     public function __construct(RequestStack $sessionEntityManagerInterface $managerCartService $cartService)
  15.     {
  16.         $this->session $session;
  17.         $this->entityManager $manager;
  18.         $this->cartService $cartService;
  19.     }
  20.     public function getFunctions(): array
  21.     {
  22.         return [
  23.             new TwigFunction('cartPreview', [$this'getCartData']),
  24.             new TwigFunction('cartTotal', [$this'getCartTotal']),
  25.             new TwigFunction('removeCartItem', [$this'removeCartItem'])
  26.         ];
  27.     }
  28.     public function getCartData(): array
  29.     {
  30.         $cart $this->session->getSession()->get('cart', []);
  31.         $cartWithData = [];
  32.         foreach ($cart as $productId => $quantity) {
  33.             // Get the product from the database
  34.             $product $this->entityManager->getRepository(Product::class)->find($productId);
  35.             $images $product->getImages();
  36.             if ($images !== null && count($images) > 0) {
  37.                 $img $images[0]->getImageName();
  38.             } else {
  39.                 $img "default.png";
  40.             }
  41.             // Only add the product if it exists in the database
  42.             if ($product) {
  43.                 $cartWithData[] = [
  44.                     'product' => $product,
  45.                     'quantity' => $quantity,
  46.                     'image' => $img
  47.                 ];
  48.             }
  49.         }
  50.         return $cartWithData;
  51.     }
  52.     public function getCartTotal(): float
  53.     {
  54.         $cartTotal 0;
  55.         foreach ($this->cartService->getCart() as $item) {
  56.             $cartTotal += $item['product']->getProductPrice() * $item['quantity'];
  57.         }
  58.         return $cartTotal;
  59.     }
  60.     public function removeCartItem(int $id): void
  61.     {
  62.         $this->cartService->remove($id);
  63.     }
  64. }