src/Twig/CartExtension.php line 39
<?phpnamespace App\Twig;use App\Entity\Product;use App\Service\Cart\CartService;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\RequestStack;use Twig\Extension\AbstractExtension;use Twig\TwigFunction;class CartExtension extends AbstractExtension{private RequestStack $session;private EntityManagerInterface $entityManager;private CartService $cartService;public function __construct(RequestStack $session, EntityManagerInterface $manager, CartService $cartService){$this->session = $session;$this->entityManager = $manager;$this->cartService = $cartService;}public function getFunctions(): array{return [new TwigFunction('cartPreview', [$this, 'getCartData']),new TwigFunction('cartTotal', [$this, 'getCartTotal']),new TwigFunction('removeCartItem', [$this, 'removeCartItem'])];}public function getCartData(): array{$cart = $this->session->getSession()->get('cart', []);$cartWithData = [];foreach ($cart as $productId => $quantity) {// Get the product from the database$product = $this->entityManager->getRepository(Product::class)->find($productId);$images = $product->getImages();if ($images !== null && count($images) > 0) {$img = $images[0]->getImageName();} else {$img = "default.png";}// Only add the product if it exists in the databaseif ($product) {$cartWithData[] = ['product' => $product,'quantity' => $quantity,'image' => $img];}}return $cartWithData;}public function getCartTotal(): float{$cartTotal = 0;foreach ($this->cartService->getCart() as $item) {$cartTotal += $item['product']->getProductPrice() * $item['quantity'];}return $cartTotal;}public function removeCartItem(int $id): void{$this->cartService->remove($id);}}