vendor/shopware/core/System/SalesChannel/Context/CachedSalesChannelContextFactory.php line 57

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\System\SalesChannel\Context;
  3. use Shopware\Core\Framework\Adapter\Cache\AbstractCacheTracer;
  4. use Shopware\Core\Framework\Adapter\Cache\CacheValueCompressor;
  5. use Shopware\Core\Framework\Log\Package;
  6. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  7. use Symfony\Contracts\Cache\CacheInterface;
  8. use Symfony\Contracts\Cache\ItemInterface;
  9. #[Package('core')]
  10. class CachedSalesChannelContextFactory extends AbstractSalesChannelContextFactory
  11. {
  12.     final public const ALL_TAG 'sales-channel-context';
  13.     /**
  14.      * @internal
  15.      *
  16.      * @param AbstractCacheTracer<SalesChannelContext> $tracer
  17.      */
  18.     public function __construct(
  19.         private readonly AbstractSalesChannelContextFactory $decorated,
  20.         private readonly CacheInterface $cache,
  21.         private readonly AbstractCacheTracer $tracer
  22.     ) {
  23.     }
  24.     public function getDecorated(): AbstractSalesChannelContextFactory
  25.     {
  26.         return $this->decorated;
  27.     }
  28.     public function create(string $tokenstring $salesChannelId, array $options = []): SalesChannelContext
  29.     {
  30.         $name self::buildName($salesChannelId);
  31.         if (!$this->isCacheable($options)) {
  32.             return $this->getDecorated()->create($token$salesChannelId$options);
  33.         }
  34.         ksort($options);
  35.         $key implode('-', [$namemd5(json_encode($options\JSON_THROW_ON_ERROR))]);
  36.         $value $this->cache->get($key, function (ItemInterface $item) use ($name$token$salesChannelId$options) {
  37.             $context $this->tracer->trace($name, fn () => $this->getDecorated()->create($token$salesChannelId$options));
  38.             $keys array_unique(array_merge(
  39.                 $this->tracer->get($name),
  40.                 [$nameself::ALL_TAG]
  41.             ));
  42.             $item->tag($keys);
  43.             return CacheValueCompressor::compress($context);
  44.         });
  45.         $context CacheValueCompressor::uncompress($value);
  46.         $context->assign(['token' => $token]);
  47.         return $context;
  48.     }
  49.     public static function buildName(string $salesChannelId): string
  50.     {
  51.         return 'context-factory-' $salesChannelId;
  52.     }
  53.     /**
  54.      * @param array<string, mixed> $options
  55.      */
  56.     private function isCacheable(array $options): bool
  57.     {
  58.         return !isset($options[SalesChannelContextService::CUSTOMER_ID])
  59.             && !isset($options[SalesChannelContextService::BILLING_ADDRESS_ID])
  60.             && !isset($options[SalesChannelContextService::SHIPPING_ADDRESS_ID]);
  61.     }
  62. }