src/Controller/HeaderController.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use App\Entity\Category;
  8. use App\Repository\ProductRepository;
  9. class HeaderController extends AbstractController
  10. {
  11.     #[Route('/header'name'app_header')]
  12.     public function index(): Response
  13.     {
  14.         // Obtener todas las categorías
  15.         $categories $this->getDoctrine()
  16.         ->getRepository(Category::class)
  17.         ->findAll();
  18.         return $this->render('header/index.html.twig', [
  19.             'controller_name' => 'HeaderController',
  20.             'categories' => $categories
  21.         ]);
  22.     }
  23.     /**
  24.      * @Route("/cartIconView", name="cartIconView")
  25.      */
  26.     public function cartIconView(SessionInterface $sessionProductRepository $productRepository)
  27.     {
  28.         // Obtener el carrito de la sesión
  29.         $cart $session->get('cart', []);
  30.         
  31.             
  32.         // Calcular el total
  33.         $total 0;
  34.         $quantity 0;
  35.         $refreshCart = [];
  36.         foreach ($cart as $item) {
  37.             $productId $item['id'];
  38.             $product $productRepository->find($productId);
  39.             if (!$product) {
  40.                 throw $this->createNotFoundException("El producto con ID $productId no existe.");
  41.                 continue;
  42.             }
  43.             if (($product->getStock() - $item['quantity']) < 0) {
  44.                 $this->addFlash('error''Lo sentimos, no hay suficiente stock del producto: "'.$product->getName().'"');
  45.                 continue;
  46.             }
  47.             $quantity += $item['quantity'];
  48.             $total += $item['price'] * $item['quantity'];
  49.             $refreshCart[] = $item;
  50.         }
  51.         $session->set('cart'$refreshCart);
  52.         return $this->render('header/header-cart.html.twig', [
  53.             'total' => number_format($total2',''.'),
  54.             'quantity' => $quantity
  55.         ]);
  56.     }
  57. }