CartLinkToken.php in Commerce Add To Cart Link 8
File
src/CartLinkToken.php
View source
<?php
namespace Drupal\commerce_add_to_cart_link;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Session\Session;
class CartLinkToken implements CartLinkTokenInterface {
protected $config;
protected $csrfTokenGenerator;
protected $currentUser;
protected $session;
public function __construct(CsrfTokenGenerator $csrf_token_generator, AccountInterface $current_user, Session $session, ConfigFactoryInterface $config_factory) {
$this->config = $config_factory
->get('commerce_add_to_cart_link.settings');
$this->csrfTokenGenerator = $csrf_token_generator;
$this->currentUser = $current_user;
$this->session = $session;
}
public function generate(ProductVariationInterface $variation) {
if (!$this
->needsCsrfProtection($this->currentUser)) {
return '';
}
if ($this->currentUser
->isAnonymous() && !$this->session
->isStarted()) {
$this->session
->start();
}
$this->session
->set('forced', TRUE);
$value = $this
->generateTokenValue($variation);
return $this->csrfTokenGenerator
->get($value);
}
public function validate(ProductVariationInterface $variation, $token) {
if (!$this
->needsCsrfProtection($this->currentUser)) {
return TRUE;
}
$value = $this
->generateTokenValue($variation);
return $this->csrfTokenGenerator
->validate($token, $value);
}
public function needsCsrfProtection(AccountInterface $account = NULL) {
if (is_null($account)) {
$account = $this->currentUser;
}
$csrf_protected_roles = $this->config
->get('csrf_token.roles');
if (empty($csrf_protected_roles)) {
return FALSE;
}
return !empty(array_intersect($csrf_protected_roles, $account
->getRoles()));
}
protected function generateTokenValue(ProductVariationInterface $variation) {
return sprintf('cart_link:%s:%s', $variation
->getProductId(), $variation
->id());
}
}