You are here

public function CartApiAccessCheck::access in Commerce Cart API 8

Checks access.

Parameters

\Symfony\Component\Routing\Route $route: The route to check against.

\Drupal\Core\Routing\RouteMatchInterface $route_match: The route match.

\Drupal\Core\Session\AccountInterface $account: The currently logged in account.

Return value

\Drupal\Core\Access\AccessResultInterface The access result.

File

src/Access/CartApiAccessCheck.php, line 52

Class

CartApiAccessCheck
Access check for the cart rest plugins.

Namespace

Drupal\commerce_cart_api\Access

Code

public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {

  // If the route has no parameters (cart collection), allow.
  $parameters = $route
    ->getOption('parameters');
  if (empty($parameters['commerce_order'])) {
    return AccessResult::allowed();
  }

  // If there is no cart, no access.
  $order = $route_match
    ->getParameter('commerce_order');
  if (!$order || !$order instanceof OrderInterface) {
    return AccessResult::forbidden();
  }

  // Carts must be a draft and flagged as a cart.
  if ($order
    ->getState()->value != 'draft' || empty($order->cart->value)) {
    return AccessResult::forbidden()
      ->addCacheableDependency($order);
  }

  // Ensure cart belongs to the current user.
  $carts = $this->cartProvider
    ->getCartIds($account);
  if (!in_array($order
    ->id(), $carts)) {
    return AccessResult::forbidden()
      ->addCacheableDependency($order);
  }

  // If there is also an order item in the route, make sure it belongs
  // to this cart as well.
  $order_item = $route_match
    ->getParameter('commerce_order_item');
  if ($order_item && $order_item instanceof OrderItemInterface) {
    if (!$order
      ->hasItem($order_item)) {
      return AccessResult::forbidden()
        ->addCacheableDependency($order_item)
        ->addCacheableDependency($order);
    }
  }
  return AccessResult::allowed()
    ->addCacheableDependency($order);
}