contacts_events-8.x-1.x-dev/src/EventSubscriber/BookingFlowRedirectSubscriber.php
src/EventSubscriber/BookingFlowRedirectSubscriber.php
<?php namespace Drupal\contacts_events\EventSubscriber; use Drupal\contacts_events\Plugin\Commerce\CheckoutFlow\BookingFlow; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Url; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; /** * Response subscriber to ensure bookings are redirected to the booking routes. */ class BookingFlowRedirectSubscriber implements EventSubscriberInterface { /** * The entity type manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** * BookingFlowRedirectSubscriber constructor. * * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * The entity type manager. */ public function __construct(EntityTypeManagerInterface $entity_type_manager) { $this->entityTypeManager = $entity_type_manager; } /** * Kernel response event handler. * * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event * Response event. */ public function checkRedirection(FilterResponseEvent $event) { $response = $event->getResponse(); // We're only interested in directs. if (!$response instanceof RedirectResponse) { return; } // And only to the checkout process. if (substr($response->getTargetUrl(), 0, 10) !== '/checkout/') { return; } $parts = explode('/', $response->getTargetUrl()); // If there are not exactly 4 parts, this is a not a checkout redirect. if (count($parts) !== 4) { return; } $order_id = $parts[2]; $order = $this->entityTypeManager ->getStorage('commerce_order') ->load($order_id); if (!$order) { return; } /** @var \Drupal\commerce_checkout\Entity\CheckoutFlowInterface $flow_entity */ $flow_entity = $order->get('checkout_flow')->entity; $flow_plugin = $flow_entity ? $flow_entity->getPlugin() : NULL; if ($flow_plugin instanceof BookingFlow) { $url = Url::fromRoute($flow_plugin::ROUTE_NAME, [ 'commerce_order' => $order_id, 'step' => $parts[3], ]); $response->setTargetUrl($url->toString()); } } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return [ KernelEvents::RESPONSE => ['checkRedirection'], ]; } }