vendor/sylius/sylius/src/Sylius/Bundle/OrderBundle/Controller/OrderItemController.php line 37

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