src/Controller/CartController.php line 107

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Article;
  4. use App\Entity\DeliveryCountry;
  5. use App\Entity\DeliveryMethod;
  6. use App\Exception\CartException;
  7. use App\Form\Handler\CartHandler;
  8. use App\Form\Type\CartType;
  9. use App\Helper\VeltisControllerTrait;
  10. use App\Repository\DeliveryCountryRepository;
  11. use App\Repository\DeliveryMethodRepository;
  12. use App\Repository\LanguageRepository;
  13. use App\Repository\ProductRepository;
  14. use App\Services\CartService;
  15. use App\Services\FacebookApiConversion;
  16. use App\Twig\AppExtension;
  17. use FOS\RestBundle\Controller\AbstractFOSRestController;
  18. use Psr\Log\LoggerInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  21. use FOS\RestBundle\Controller\Annotations as Rest;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  23. use Symfony\Component\BrowserKit\Response;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use FOS\RestBundle\View\View;
  28. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  29. use Symfony\Contracts\Translation\TranslatorInterface;
  30. class CartController  extends AbstractController
  31. {
  32.     use VeltisControllerTrait;
  33.     /**
  34.      * @Route("/cart", name="cart")
  35.      */
  36.     public function cartAction(Request $requestCartService $cartServiceProductRepository $productRepositoryLanguageRepository $languageRepositoryDeliveryMethodRepository $deliveryMethodRepositoryCartHandler $cartHandler)
  37.     {
  38.         $language $this->resolveLanguage($request->getLocale());
  39.         $cartService->cartRecalculate($language);
  40.         $cart $cartService->getOrCreateCart();
  41.         $showNotification 0;
  42.         if ($cart->getRemovedProductsNotification()) {
  43.             $showNotification 1;
  44.             $cart->setRemovedProductsNotification(0);
  45.             $this->em()->persist($cart);
  46.             $this->em()->flush();
  47.         }
  48.         $cartService->removeInvisible($cart);
  49.         $form $this->createForm(CartType::class, $cart);
  50.         $form->handleRequest($request);
  51.         if ($form->isSubmitted()) {
  52.             if ($form->isValid()) {
  53.                 $cartHandler->handle($cart);
  54.                 //return $this->redirectToRoute('cart');
  55.                 header("Location: /cart");
  56.                 exit();
  57.             }
  58.         }
  59.         $cs $cartService->getCrossSellingProducts($cartService->getCart());
  60.         $ids = [];
  61.         foreach ($cs as $r) {
  62.             $ids[] = $r->getId();
  63.         }
  64.         $search = [];
  65.         $search['locale'] = $request->getLocale();
  66.         if (count($ids)) {
  67.             $queryCrossSelling $productRepository->getForCrossSelling($ids$search)->getQuery()->getResult();
  68.         } else {
  69.             $queryCrossSelling = [];
  70.         }
  71.         $paymentId null;
  72.         if ($cartService->getCart() and $cartService->getCart()->getPaymentMethod()) {
  73.             $paymentId $cartService->getCart()->getPaymentMethod()->getId();
  74.         }
  75.         $deliveryId null;
  76.         if ($cartService->getCart() and $cartService->getCart()->getDeliveryMethod()) {
  77.             $deliveryId $cartService->getCart()->getDeliveryMethod()->getId();
  78.         }
  79.         $sumInfo $cartService->ajaxCalculateSum($deliveryId$paymentId);
  80.         $shoppingArticle $this->em()->getRepository(Article::class)->find(Article::getShoppingArticleId($request->getLocale()));
  81.         $view $this->render('frontend/cart/cart.html.twig', [
  82.             'form' => $form->createView(),
  83.             'shoppingArticle' => $shoppingArticle,
  84.             'countries' => $languageRepository->getAll($cartService->getLocale())->getQuery()->getResult(),
  85.             'defaultCountry' => [],
  86.             'cartSpecialDeliveryMethods' => $cartService->getSpecialDeliveryMethodsIds($cartService->getCart()),
  87.             'cart' => $cartService->getCart(),
  88.             'language' => $language,
  89.             'sumInfo' => $sumInfo,
  90.             'showNotification' => $showNotification,
  91.             'crossSelling' => $queryCrossSelling,
  92.             'cartProducts' => $cartService->getCartProducts(),
  93.             'locale' => $cartService->getLocale(),
  94.             'currency' => $this->get('session')->get('currency'),
  95.             'deliveryMethods' => $deliveryMethodRepository->getDeliveryMethodsForLanguage($language)->getQuery()->getResult()
  96.         ]);
  97.         $view->headers->set('Cache-Control''no-cache, no-store, must-revalidate');
  98.         $view->headers->set('Pragma''no-cache');
  99.         $view->headers->set('Expires''0');
  100.         return $view;
  101.     }
  102.     /**
  103.      * When user change delviery country -> reload delivery methods
  104.      * @Route("/cart/load-delivery-methods", name="load_delivery_methods")
  105.      */
  106.     public function ajaxDeliveryMethodsAction(Request $requestCartService $cartServiceDeliveryMethodRepository $deliveryMethodRepository) {
  107.         $id $request->request->get('id');
  108.         /** @var $deliveryCountry DeliveryCountry */
  109.         $deliveryCountry $this->get(DeliveryCountryRepository::class)->getRepository()->find($id);
  110.         return $this->render('frontend/cart/_deliveryMethods.html.twig', [
  111.             'defaultCountry' => $deliveryCountry,
  112.             'locale' => $cartService->getLocale(),
  113.             'currency' => $this->get('session')->get('currency'),
  114.             'deliveryMethods' => $deliveryMethodRepository->getDeliveryMethodsForCountry($deliveryCountry)->getQuery()->getResult()
  115.         ]);
  116.     }
  117.     /**
  118.      * When user change delivery method - load associated payment methods
  119.      * @Route("/cart/load-payment-methods", name="load_payment_methods")
  120.      */
  121.     public function ajaxPaymentMethodsAction(Request $requestCartService $cartServiceDeliveryMethodRepository $deliveryMethodRepository) {
  122.         $id $request->request->get('id');
  123.         /** @var $deliveryMethod DeliveryMethod */
  124.         $deliveryMethod $deliveryMethodRepository->getRepository()->find($id);
  125.         $payments $deliveryMethod->getPaymentMethods();
  126.         return $this->render('frontend/cart/_paymentMethods.html.twig', [
  127.             'locale' => $cartService->getLocale(),
  128.             'currency' => $this->get('session')->get('currency'),
  129.             'payments' => $payments
  130.         ]);
  131.     }
  132.     /**
  133.      * When user change delivery method or payment method - load dynamically calculated sum
  134.      * @Route("/cart/calculate-sum", name="ajax_calculate_sum")
  135.      */
  136.     public function ajaxDynamicCalculateSumAction(Request $requestCartService $cartServiceAppExtension $appExtension) {
  137.         $deliveryId $request->request->get('deliveryId');
  138.         $paymentId $request->request->get('paymentId');
  139.         $sum $cartService->ajaxCalculateSum($deliveryId$paymentId);
  140.         $formatSum $appExtension->formatPrice($sum['sum'], $cartService->getCurrency());
  141.         $formatSumWithRebate $appExtension->formatPrice($sum['sumWithRebate'], $cartService->getCurrency());
  142.         $formatSavings $appExtension->formatPrice($sum['sumWithRebate'] - $sum['sum'], $cartService->getCurrency());
  143.         return new JsonResponse(['savings'=>$formatSavings'sum'=>$formatSum'sumWithRebate'=>$formatSumWithRebate]);
  144.     }
  145.     /**
  146.      * Next click button Handler - go to register or login page
  147.      * @Route("/cart/checkout-handler", name="ajax_save_cart")
  148.      */
  149.     public function ajaxSaveCartAction(Request $requestCartService $cartService) {
  150.         $cart $cartService->getCart();
  151.         $deliveryId $request->request->get('deliveryId');
  152.         $paymentId $request->request->get('paymentId');
  153.         $cartService->prepareToCheckout($deliveryId$paymentId);
  154.         return new JsonResponse([]);
  155.     }
  156.     /**
  157.      * When user click discard rebate code in the cart
  158.      * @Route("/cart/discard-rebate-code", name="discard_cart_rebate_code")
  159.      */
  160.     public function discardRebateCode(Request $requestCartService $cartService) {
  161.         $cartService->discardRebateCode();
  162.         return $this->redirectToRoute('cart');
  163.     }
  164.     /**
  165.      * @Route("/cart/add", name="add_to_cart")
  166.      */
  167.     public function addToCartAction(Request $requestLoggerInterface $loggerCartService $cartServiceTranslatorInterface $translatorFacebookApiConversion $facebookApiConversion): JsonResponse {
  168.         $product $cartService->getProductEntity($request->request->get('product_id'));
  169.         $quantity $request->request->get('quantity');
  170.         if (!is_numeric($quantity)) {
  171.             $quantity 1;
  172.         }
  173.         if ($cartService->isMaxQuantityExceeded($product$quantity)) {
  174.             return new JsonResponse(['message'=>$translator->trans('max_quantity_exceeded_message', ['%count%'=>$product->getMaxQuantity()], 'store'$request->getLocale()), 'error'=>1]);
  175.         }
  176.         if ($request->getLocale() != 'pl') {
  177.             try {
  178.                 $facebookApiConversion->createFbEvent('AddToCart');
  179.             } catch (\Exception $exception) {
  180.                 //
  181.             }
  182.         }
  183.         try {
  184.             $cartService->addToCart($request);
  185.         } catch (CartException $e) {
  186.             $logger->critical($e->getMessage());
  187.             return new JsonResponse(['message'=>$translator->trans('session_invalidated', [], 'store'$request->getLocale()), 'error'=>1]);
  188.         }
  189.         return new JsonResponse(['message'=>'ok''error'=>0'result'=>$cartService->isMaxQuantityExceeded($product$quantity)]);
  190.     }
  191.     private function generateSessionCode() {
  192.         $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  193.         $randomString '';
  194.         for ($i 0$i 36$i++) {
  195.             $randomString .= $characters[rand(0strlen($characters) - 1)];
  196.         }
  197.         return $randomString;
  198.     }
  199.     /**
  200.      * @Route("/cart/remove-element", name="remove_from_cart")
  201.      */
  202.     public function removeFromCartAction(Request $requestCartService $cartService)
  203.     {
  204.         $cartService->removeFromCart($request);
  205.         return new JsonResponse(['message'=>'ok']);
  206.     }
  207.     /**
  208.      * @Route("/cart/update-quantity-cart", name="update_quantity_cart")
  209.      */
  210.     public function updateQuantityAction(Request $requestCartService $cartServiceTranslatorInterface $translator)
  211.     {
  212.         $product $cartService->getProductEntity($request->request->get('product_id'));
  213.         $quantity $request->request->get('quantity');
  214.         if (!is_numeric($quantity)) {
  215.             $quantity 1;
  216.         }
  217.         if ($quantity <= 0) {
  218.             return new JsonResponse(['message'=>$translator->trans('invalid_number', [], 'store'$request->getLocale()), 'error'=>1]);
  219.         }
  220.         if ($cartService->isMaxQuantityExceeded($product$quantity)) {
  221.             return new JsonResponse(['message'=>$translator->trans('max_quantity_exceeded_message', ['%count%'=>$product->getMaxQuantity()], 'store'$request->getLocale()), 'error'=>1]);
  222.         }
  223.         if ($cartService->isSubProductInCart($request)) {
  224.             return new JsonResponse(['message'=>$translator->trans('max_quantity_exceeded_message', ['%count%'=>1], 'store'$request->getLocale()), 'error'=>1]);
  225.         }
  226.         $cartService->updateQuantityCart($request);
  227.         return new JsonResponse(['message'=>'ok''error'=>0'result'=>$cartService->isMaxQuantityExceeded($product$quantity)]);
  228.     }
  229. }