CartTokenSession.php in Commerce Cart API 8
File
src/CartTokenSession.php
View source
<?php
namespace Drupal\commerce_cart_api;
use Drupal\commerce_cart\CartSessionInterface;
use Drupal\Core\TempStore\SharedTempStoreFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
final class CartTokenSession implements CartSessionInterface {
const HEADER_NAME = 'Commerce-Cart-Token';
const QUERY_NAME = 'cartToken';
private $inner;
private $requestStack;
private $tempStore;
public function __construct(CartSessionInterface $inner, RequestStack $request_stack, SharedTempStoreFactory $temp_store_factory) {
$this->inner = $inner;
$this->requestStack = $request_stack;
$this->tempStore = $temp_store_factory
->get('commerce_cart_api_tokens');
}
public function getCartIds($type = self::ACTIVE) {
if ($this
->getCurrentRequestCartToken() === NULL) {
return $this->inner
->getCartIds($type);
}
$data = $this
->getTokenCartData();
return $data[$type];
}
public function addCartId($cart_id, $type = self::ACTIVE) {
$this->inner
->addCartId($cart_id, $type);
if ($this
->getCurrentRequestCartToken() !== NULL) {
$data = $this
->getTokenCartData();
$ids = $data[$type];
$ids[] = $cart_id;
$data[$type] = $ids;
$this
->setTokenCartData($data);
}
}
public function hasCartId($cart_id, $type = self::ACTIVE) {
if ($this
->getCurrentRequestCartToken() === NULL) {
return $this->inner
->hasCartId($cart_id, $type);
}
$data = $this
->getTokenCartData();
$ids = $data[$type];
return in_array($cart_id, $ids, TRUE);
}
public function deleteCartId($cart_id, $type = self::ACTIVE) {
$this->inner
->deleteCartId($cart_id, $type);
if ($this
->getCurrentRequestCartToken() !== NULL) {
$data = $this
->getTokenCartData();
$ids = $data[$type];
$ids = array_diff($ids, [
$cart_id,
]);
$data[$type] = $ids;
$this
->setTokenCartData($data);
}
}
private function getCurrentRequestCartToken() {
$request = $this->requestStack
->getCurrentRequest();
assert($request instanceof Request);
return $request->headers
->get(static::HEADER_NAME);
}
private function getTokenCartData() {
$defaults = [
static::ACTIVE => [],
static::COMPLETED => [],
];
$token = $this
->getCurrentRequestCartToken();
if (empty($token)) {
return $defaults;
}
return $this->tempStore
->get($token) ?: $defaults;
}
private function setTokenCartData(array $data) {
$token = $this
->getCurrentRequestCartToken();
if (!empty($token)) {
$this->tempStore
->set($token, $data);
}
}
}