src/Controller/CartController.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Cart;
  4. use App\Entity\OrderItem;
  5. use App\Form\AddToCartType;
  6. use App\Manager\CartManager;
  7. use Doctrine\Persistence\ManagerRegistry;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. class CartController extends AbstractController
  13. {
  14. /**
  15. * @Route("/cart", name="cart")
  16. */
  17. public function index(Request $request): Response
  18. {
  19. if ($request->isXmlHttpRequest()) {
  20. return $this->render('cart/partials/_cart_section.html.twig');
  21. }
  22. return $this->render('cart/index.html.twig', [
  23. 'controller_name' => 'CartController',
  24. 'additional_services' => [],
  25. ]);
  26. }
  27. /**
  28. * @Route("/cart/{id}/update", name="cart_update")
  29. */
  30. public function updateCart(OrderItem $item, Request $request, ManagerRegistry $registry, ProductController $controller): Response
  31. {
  32. $form = $this->createForm(AddToCartType::class, $item, [
  33. 'action' => $this->generateUrl('cart_update', ['id' => $item->getId()]).'?partial=true',
  34. ]);
  35. $form->handleRequest($request);
  36. if ($request->get('partial') && $request->isXmlHttpRequest()) {
  37. $payment_option = $form->get('paymentOption')->getData();
  38. if ($form->isSubmitted() && $form->isValid()) {
  39. $controller->setInstallmentOption($item , $payment_option,
  40. $item->getProducts()->getInstallments()->toArray());
  41. $registry->getManager()->flush();
  42. return new Response('', \Symfony\Component\HttpFoundation\Response::HTTP_OK);
  43. }
  44. return $this->renderForm('order_item/_form.html.twig', [
  45. 'form' => $form,
  46. ]);
  47. }
  48. return new Response('', \Symfony\Component\HttpFoundation\Response::HTTP_UNAUTHORIZED);
  49. }
  50. /**
  51. * @Route("/removeFromCart", name="removeFromCart")
  52. */
  53. public function removeFromCart(Request $request, CartManager $cartManager): Response
  54. {
  55. $itemId = $request->request->get('itemId');
  56. if (!empty($itemId)) {
  57. $cart = $cartManager->getCurrentCart();
  58. $items = $cart->getOrderItems();
  59. foreach ($items as $c_item) {
  60. if ($c_item->getProducts()->getId() == $itemId) {
  61. $cart->removeOrderItem($c_item);
  62. }
  63. }
  64. $cartManager->save($cart);
  65. }
  66. return $this->render('cart/partials/_cart_section.html.twig');
  67. }
  68. }