commercetools-8.x-1.2-alpha1/src/Cache/Context/CartCacheContext.php

src/Cache/Context/CartCacheContext.php
<?php

namespace Drupal\commercetools\Cache\Context;

use Drupal\commercetools\Cache\CacheableCommercetoolsGraphQlResponse;
use Drupal\commercetools\CommercetoolsApiServiceInterface;
use Drupal\commercetools\CommercetoolsCarts;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;

/**
 * Defines the CartCacheContext service, for "per cart" caching.
 *
 * Cache context ID: 'cart'.
 */
class CartCacheContext implements CacheContextInterface {

  /**
   * Constructs a new CartCacheContext object.
   *
   * @param \Drupal\commercetools\CommercetoolsCarts $ctCart
   *   The commercetools cart service.
   */
  public function __construct(
    protected CommercetoolsCarts $ctCart,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Current cart IDs');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return $this->ctCart->getCurrentCartId();
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    $metadata = new CacheableMetadata();
    $cart = $this->getCurrentCart();
    if (!empty($cart['id'])) {
      $metadata->addCacheTags([
        'config:' . CommercetoolsApiServiceInterface::CONFIGURATION_NAME,
        CacheableCommercetoolsGraphQlResponse::CACHE_TAG_CART_PREFIX . $cart['id'],
      ]);
    }
    return $metadata;
  }

  /**
   * Get the user's current cart.
   */
  protected function getCurrentCart(): array|null {
    $cart = $this->ctCart->getCurrentCart();
    return isset($cart) && $cart->getData()
      ? $cart->getData()
      : NULL;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc