You are here

public function CommerceCartRedirectionSubscriber::tryRedirectToCheckout in Commerce Cart Redirection 8.2

Conditionally skip cart and send user to checkout.

If the added product meets criteria set in the config form then redirect.

Parameters

\Drupal\commerce_cart\Event\CartEntityAddEvent $event: The add to cart event.

File

src/EventSubscriber/CommerceCartRedirectionSubscriber.php, line 54

Class

CommerceCartRedirectionSubscriber

Namespace

Drupal\commerce_cart_redirection\EventSubscriber

Code

public function tryRedirectToCheckout(CartEntityAddEvent $event) {
  $redirect = FALSE;
  $purchased_entity = $event
    ->getEntity();

  /** @var \Drupal\Core\Config\Config $config */
  $config = \Drupal::config('commerce_cart_redirection.settings');
  $active_bundles = $config
    ->get('product_bundles');
  $negate = $config
    ->get('negate_product_bundles');
  $purchased_bundle = $purchased_entity
    ->bundle();
  if (isset($active_bundles[$purchased_bundle]) && $active_bundles[$purchased_bundle] !== 0) {
    if (!$negate) {
      $redirect = TRUE;
    }
  }
  else {
    if ($negate) {
      $redirect = TRUE;
    }
  }
  if ($redirect) {

    // Set a default so we always end up somewhere useful.
    $redirection_url = Url::fromRoute('commerce_checkout.form', [
      'commerce_order' => $event
        ->getCart()
        ->id(),
    ])
      ->toString();
    switch ($config
      ->get('redirection_route_path')) {
      case 'other':

        // @TODO add some sort of sanity checking.
        if (!empty($config
          ->get('redirection_route_path_other')) && UrlHelper::isValid($config
          ->get('redirection_route_path_other'))) {
          $redirection_url = $config
            ->get('redirection_route_path_other');
        }
        break;
      case 'cart':
        $redirection_url = Url::fromRoute('commerce_cart.page')
          ->toString();
        break;
      case 'checkout':
      default:
    }
    $this->requestStack
      ->getCurrentRequest()->attributes
      ->set('commerce_cart_redirection_url', $redirection_url);
  }
}