<?php
namespace App\Form\EventListener;
use App\Entity\OrderItem;
use App\Entity\Orders;
use App\Factory\OrderFactory;
use App\Manager\CartManager;
use App\Storage\CartSessionStorage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class RemoveCartItemListener implements EventSubscriberInterface
{
public EntityManagerInterface $em;
private CartManager $cartManager;
private CartSessionStorage $cartStorage;
public function __construct(EntityManagerInterface $em, CartManager $cartManager, CartSessionStorage $cartStorage)
{
$this->em = $em;
$this->cartManager = $cartManager;
$this->cartStorage = $cartStorage;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents(): array
{
return [FormEvents::POST_SUBMIT => 'postSubmit'];
}
/**
* Removes items from the cart based on the data sent from the user.
* @param FormEvent $event
*/
public function postSubmit(FormEvent $event): void
{
$form = $event->getForm();
$cart = $form->getData();
if (!$cart instanceof Orders) {
return;
}
// Removes items from the cart
foreach ($form->get('items')->all() as $child) {
if ($child->get('remove')->isClicked()) {
$id = $child->getNormData()->getId();
$c3 = $this->em->getRepository(OrderItem::class)->findOneBy(['id'=>$id]);
$cart->removeItem($child->getData());
$this->em->remove($c3);
/* $this->em->persist($cart);
$this->em->flush();
$this->em->clear();*/
$this->em->flush();
break;
}
}
}
}