You are here

public function CartLinkToken::generate in Commerce Add To Cart Link 8

Same name and namespace in other branches
  1. 2.x src/CartLinkToken.php \Drupal\commerce_add_to_cart_link\CartLinkToken::generate()

Generates a token for the given product variation.

The token is added to the add to cart link and tied to the user session.

Parameters

\Drupal\commerce_product\Entity\ProductVariationInterface $variation: The product variation.

Return value

string The generated token.

Overrides CartLinkTokenInterface::generate

File

src/CartLinkToken.php, line 66

Class

CartLinkToken
Default cart link token service implementation.

Namespace

Drupal\commerce_add_to_cart_link

Code

public function generate(ProductVariationInterface $variation) {
  if (!$this
    ->needsCsrfProtection($this->currentUser)) {
    return '';
  }

  // Ensure that an anonymous user has a session created, as we need to
  // generate a token, which won't work without having a session.
  if ($this->currentUser
    ->isAnonymous() && !$this->session
    ->isStarted()) {
    $this->session
      ->start();
  }
  $this->session
    ->set('forced', TRUE);
  $value = $this
    ->generateTokenValue($variation);
  return $this->csrfTokenGenerator
    ->get($value);
}