vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/Checkout/CheckoutResolver.php line 36

Open in your IDE?
  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\CoreBundle\Checkout;
  12. use SM\Factory\FactoryInterface;
  13. use Sylius\Component\Core\Model\OrderInterface;
  14. use Sylius\Component\Order\Context\CartContextInterface;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\RequestMatcherInterface;
  19. use Symfony\Component\HttpKernel\Event\RequestEvent;
  20. use Symfony\Component\HttpKernel\KernelEvents;
  21. final class CheckoutResolver implements EventSubscriberInterface
  22. {
  23. public function __construct(
  24. private CartContextInterface $cartContext,
  25. private CheckoutStateUrlGeneratorInterface $urlGenerator,
  26. private RequestMatcherInterface $requestMatcher,
  27. private FactoryInterface $stateMachineFactory,
  28. ) {
  29. }
  30. public function onKernelRequest(RequestEvent $event): void
  31. {
  32. if (\method_exists($event, 'isMainRequest')) {
  33. $isMainRequest = $event->isMainRequest();
  34. } else {
  35. $isMainRequest = $event->isMasterRequest();
  36. }
  37. if (!$isMainRequest) {
  38. return;
  39. }
  40. $request = $event->getRequest();
  41. if (!$this->requestMatcher->matches($request)) {
  42. return;
  43. }
  44. /** @var OrderInterface $order */
  45. $order = $this->cartContext->getCart();
  46. if ($order->isEmpty()) {
  47. $event->setResponse(new RedirectResponse($this->urlGenerator->generateForCart()));
  48. }
  49. $stateMachine = $this->stateMachineFactory->get($order, $this->getRequestedGraph($request));
  50. if ($stateMachine->can($this->getRequestedTransition($request))) {
  51. return;
  52. }
  53. $event->setResponse(new RedirectResponse($this->urlGenerator->generateForOrderCheckoutState($order)));
  54. }
  55. public static function getSubscribedEvents(): array
  56. {
  57. return [
  58. KernelEvents::REQUEST => 'onKernelRequest',
  59. ];
  60. }
  61. private function getRequestedGraph(Request $request): string
  62. {
  63. return $request->attributes->get('_sylius')['state_machine']['graph'];
  64. }
  65. private function getRequestedTransition(Request $request): string
  66. {
  67. return $request->attributes->get('_sylius')['state_machine']['transition'];
  68. }
  69. }