src/Controller/Shop/OrderItemController.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Shop;
  3. use App\Entity\Order\OrderItemUnit;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use FOS\RestBundle\View\View;
  6. use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
  7. use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;
  8. use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
  9. use Sylius\Component\Core\Model\ShipmentInterface;
  10. use Sylius\Component\Order\CartActions;
  11. use Sylius\Component\Order\Context\CartContextInterface;
  12. use Sylius\Component\Order\Model\OrderInterface;
  13. use Sylius\Component\Order\Model\OrderItemInterface;
  14. use Sylius\Component\Order\Modifier\OrderItemQuantityModifierInterface;
  15. use Sylius\Component\Order\Modifier\OrderModifierInterface;
  16. use Sylius\Component\Order\Repository\OrderRepositoryInterface;
  17. use Symfony\Component\Form\FormError;
  18. use Symfony\Component\Form\FormFactoryInterface;
  19. use Symfony\Component\Form\FormInterface;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\HttpKernel\Exception\HttpException;
  23. use Symfony\Component\Validator\ConstraintViolationListInterface;
  24. class OrderItemController extends ResourceController
  25. {
  26.     public function addAction(Request $request): Response
  27.     {
  28.         $cart $this->getCurrentCart();
  29.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  30.         $this->isGrantedOr403($configurationCartActions::ADD);
  31.         /** @var OrderItemInterface $orderItem */
  32.         $orderItem $this->newResourceFactory->create($configuration$this->factory);
  33.         $this->getQuantityModifier()->modify($orderItem1);
  34.         $form $this->getFormFactory()->create(
  35.             $configuration->getFormType(),
  36.             $this->createAddToCartCommand($cart$orderItem),
  37.             $configuration->getFormOptions()
  38.         );
  39.         if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
  40.             /** @var AddToCartCommandInterface $addToCartCommand */
  41.             $addToCartCommand $form->getData();
  42.             $errors $this->getCartItemErrors($addToCartCommand->getCartItem());
  43.             if (count($errors)) {
  44.                 $form $this->getAddToCartFormWithErrors($errors$form);
  45.                 return $this->handleBadAjaxRequestView($configuration$form);
  46.             }
  47.             $event $this->eventDispatcher->dispatchPreEvent(CartActions::ADD$configuration$orderItem);
  48.             if ($event->isStopped() && !$configuration->isHtmlRequest()) {
  49.                 throw new HttpException($event->getErrorCode(), $event->getMessage());
  50.             }
  51.             if ($event->isStopped()) {
  52.                 $this->flashHelper->addFlashFromEvent($configuration$event);
  53.                 return $this->redirectHandler->redirectToIndex($configuration$orderItem);
  54.             }
  55.             $this->getOrderModifier()->addToOrder($addToCartCommand->getCart(), $addToCartCommand->getCartItem());
  56.             $cartManager $this->getCartManager();
  57.             $cartManager->persist($cart);
  58.             $cartManager->flush();
  59.             $resourceControllerEvent $this->eventDispatcher->dispatchPostEvent(CartActions::ADD$configuration$orderItem);
  60.             if ($resourceControllerEvent->hasResponse()) {
  61.                 return $resourceControllerEvent->getResponse();
  62.             }
  63.             $this->flashHelper->addSuccessFlash($configurationCartActions::ADD$orderItem);
  64.             if ($request->isXmlHttpRequest()) {
  65.                 return $this->viewHandler->handle($configurationView::create([], Response::HTTP_CREATED));
  66.             }
  67.             return $this->redirectHandler->redirectToResource($configuration$orderItem);
  68.         }
  69.         if (!$configuration->isHtmlRequest()) {
  70.             return $this->handleBadAjaxRequestView($configuration$form);
  71.         }
  72.         return $this->render(
  73.             $configuration->getTemplate(CartActions::ADD '.html'),
  74.             [
  75.                 'configuration' => $configuration,
  76.                 $this->metadata->getName() => $orderItem,
  77.                 'form' => $form->createView(),
  78.             ]
  79.         );
  80.     }
  81.     public function removeAction(Request $request): Response
  82.     {
  83.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  84.         $this->isGrantedOr403($configurationCartActions::REMOVE);
  85.         /** @var OrderItemInterface $orderItem */
  86.         $orderItem $this->findOr404($configuration);
  87.         /** @var ShipmentInterface $shipment */
  88.         $shipment $orderItem->getUnits()->first()->getShipment();
  89.         $event $this->eventDispatcher->dispatchPreEvent(CartActions::REMOVE$configuration$orderItem);
  90.         if ($configuration->isCsrfProtectionEnabled() && !$this->isCsrfTokenValid((string) $orderItem->getId(), (string) $request->request->get('_csrf_token'))) {
  91.             throw new HttpException(Response::HTTP_FORBIDDEN'Invalid csrf token.');
  92.         }
  93.         if ($event->isStopped() && !$configuration->isHtmlRequest()) {
  94.             throw new HttpException($event->getErrorCode(), $event->getMessage());
  95.         }
  96.         if ($event->isStopped()) {
  97.             $this->flashHelper->addFlashFromEvent($configuration$event);
  98.             return $this->redirectHandler->redirectToIndex($configuration$orderItem);
  99.         }
  100.         $cart $this->getCurrentCart();
  101.         if ($cart !== $orderItem->getOrder()) {
  102.             $this->addFlash('error'$this->get('translator')->trans('sylius.cart.cannot_modify', [], 'flashes'));
  103.             if (!$configuration->isHtmlRequest()) {
  104.                 return $this->viewHandler->handle($configurationView::create(nullResponse::HTTP_NO_CONTENT));
  105.             }
  106.             return $this->redirectHandler->redirectToIndex($configuration$orderItem);
  107.         }
  108.         $this->getOrderModifier()->removeFromOrder($cart$orderItem);
  109.         $this->repository->remove($orderItem);
  110.         $cartManager $this->getCartManager();
  111.         $cartManager->persist($cart);
  112.         $cartManager->flush();
  113.         $this->eventDispatcher->dispatchPostEvent(CartActions::REMOVE$configuration$orderItem);
  114.         if (!$configuration->isHtmlRequest()) {
  115.             return $this->viewHandler->handle($configurationView::create(nullResponse::HTTP_NO_CONTENT));
  116.         }
  117.         $this->flashHelper->addSuccessFlash($configurationCartActions::REMOVE$orderItem);
  118.         // Custom
  119.         $this->checkForOrphanShipments($shipment);
  120.         return $this->redirectHandler->redirectToIndex($configuration$orderItem);
  121.     }
  122.     /**
  123.      * @param ShipmentInterface $shipment
  124.      * @return void
  125.      */
  126.     private function checkForOrphanShipments(ShipmentInterface $shipment): void
  127.     {
  128.         if (empty($this->manager->getRepository(OrderItemUnit::class)->findBy(['shipment' => $shipment->getId()]))) {
  129.             $this->manager->remove($shipment);
  130.             $this->manager->flush();
  131.         }
  132.     }
  133.     protected function getOrderRepository(): OrderRepositoryInterface
  134.     {
  135.         return $this->get('sylius.repository.order');
  136.     }
  137.     protected function redirectToCartSummary(RequestConfiguration $configuration): Response
  138.     {
  139.         if (null === $configuration->getParameters()->get('redirect')) {
  140.             return $this->redirectHandler->redirectToRoute($configuration$this->getCartSummaryRoute());
  141.         }
  142.         return $this->redirectHandler->redirectToRoute($configuration$configuration->getParameters()->get('redirect'));
  143.     }
  144.     protected function getCartSummaryRoute(): string
  145.     {
  146.         return 'sylius_cart_summary';
  147.     }
  148.     protected function getCurrentCart(): OrderInterface
  149.     {
  150.         return $this->getContext()->getCart();
  151.     }
  152.     protected function getContext(): CartContextInterface
  153.     {
  154.         return $this->get('sylius.context.cart');
  155.     }
  156.     protected function createAddToCartCommand(OrderInterface $cartOrderItemInterface $cartItem): AddToCartCommandInterface
  157.     {
  158.         return $this->get('sylius.factory.add_to_cart_command')->createWithCartAndCartItem($cart$cartItem);
  159.     }
  160.     protected function getFormFactory(): FormFactoryInterface
  161.     {
  162.         return $this->get('form.factory');
  163.     }
  164.     protected function getQuantityModifier(): OrderItemQuantityModifierInterface
  165.     {
  166.         return $this->get('sylius.order_item_quantity_modifier');
  167.     }
  168.     protected function getOrderModifier(): OrderModifierInterface
  169.     {
  170.         return $this->get('sylius.order_modifier');
  171.     }
  172.     protected function getCartManager(): EntityManagerInterface
  173.     {
  174.         return $this->get('sylius.manager.order');
  175.     }
  176.     protected function getCartItemErrors(OrderItemInterface $orderItem): ConstraintViolationListInterface
  177.     {
  178.         return $this
  179.             ->get('validator')
  180.             ->validate($orderItemnull$this->getParameter('sylius.form.type.order_item.validation_groups'))
  181.         ;
  182.     }
  183.     protected function getAddToCartFormWithErrors(ConstraintViolationListInterface $errorsFormInterface $form): FormInterface
  184.     {
  185.         foreach ($errors as $error) {
  186.             $formSelected = empty($error->getPropertyPath())
  187.                 ? $form->get('cartItem')
  188.                 : $form->get('cartItem')->get($error->getPropertyPath());
  189.             $formSelected->addError(new FormError($error->getMessage()));
  190.         }
  191.         return $form;
  192.     }
  193.     protected function handleBadAjaxRequestView(RequestConfiguration $configurationFormInterface $form): Response
  194.     {
  195.         return $this->viewHandler->handle(
  196.             $configuration,
  197.             View::create($formResponse::HTTP_BAD_REQUEST)->setData(['errors' => $form->getErrors(truetrue)])
  198.         );
  199.     }
  200. }