src/Core/Content/Product/SalesChannel/CrossSelling/CachedProductCrossSellingRoute.php line 61

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Product\SalesChannel\CrossSelling;
  3. use Shopware\Core\Content\Product\Events\CrossSellingRouteCacheKeyEvent;
  4. use Shopware\Core\Content\Product\Events\CrossSellingRouteCacheTagsEvent;
  5. use Shopware\Core\Framework\Adapter\Cache\AbstractCacheTracer;
  6. use Shopware\Core\Framework\Adapter\Cache\CacheValueCompressor;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\RuleAreas;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\Log\Package;
  11. use Shopware\Core\Framework\Util\Json;
  12. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Contracts\Cache\CacheInterface;
  16. use Symfony\Contracts\Cache\ItemInterface;
  17. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  18. #[Route(defaults: ['_routeScope' => ['store-api']])]
  19. #[Package('inventory')]
  20. class CachedProductCrossSellingRoute extends AbstractProductCrossSellingRoute
  21. {
  22.     /**
  23.      * @internal
  24.      *
  25.      * @param AbstractCacheTracer<ProductCrossSellingRouteResponse> $tracer
  26.      * @param array<string> $states
  27.      */
  28.     public function __construct(private readonly AbstractProductCrossSellingRoute $decorated, private readonly CacheInterface $cache, private readonly EntityCacheKeyGenerator $generator, private readonly AbstractCacheTracer $tracer, private readonly EventDispatcherInterface $dispatcher, private readonly array $states)
  29.     {
  30.     }
  31.     public function getDecorated(): AbstractProductCrossSellingRoute
  32.     {
  33.         return $this->decorated;
  34.     }
  35.     public static function buildName(string $id): string
  36.     {
  37.         return 'cross-selling-route-' $id;
  38.     }
  39.     #[Route(path'/store-api/product/{productId}/cross-selling'name'store-api.product.cross-selling'methods: ['POST'], defaults: ['_entity' => 'product'])]
  40.     public function load(string $productIdRequest $requestSalesChannelContext $contextCriteria $criteria): ProductCrossSellingRouteResponse
  41.     {
  42.         if ($context->hasState(...$this->states)) {
  43.             return $this->getDecorated()->load($productId$request$context$criteria);
  44.         }
  45.         $key $this->generateKey($productId$request$context$criteria);
  46.         if ($key === null) {
  47.             return $this->getDecorated()->load($productId$request$context$criteria);
  48.         }
  49.         $value $this->cache->get($key, function (ItemInterface $item) use ($productId$request$context$criteria) {
  50.             $name self::buildName($productId);
  51.             $response $this->tracer->trace($name, fn () => $this->getDecorated()->load($productId$request$context$criteria));
  52.             $item->tag($this->generateTags($productId$request$response$context$criteria));
  53.             return CacheValueCompressor::compress($response);
  54.         });
  55.         return CacheValueCompressor::uncompress($value);
  56.     }
  57.     private function generateKey(string $productIdRequest $requestSalesChannelContext $contextCriteria $criteria): ?string
  58.     {
  59.         $parts = [
  60.             $this->generator->getCriteriaHash($criteria),
  61.             $this->generator->getSalesChannelContextHash($context, [RuleAreas::PRODUCT_AREA]),
  62.         ];
  63.         $event = new CrossSellingRouteCacheKeyEvent($productId$parts$request$context$criteria);
  64.         $this->dispatcher->dispatch($event);
  65.         if (!$event->shouldCache()) {
  66.             return null;
  67.         }
  68.         return self::buildName($productId) . '-' md5(Json::encode($event->getParts()));
  69.     }
  70.     /**
  71.      * @return array<string>
  72.      */
  73.     private function generateTags(string $productIdRequest $requestProductCrossSellingRouteResponse $responseSalesChannelContext $contextCriteria $criteria): array
  74.     {
  75.         $tags array_merge(
  76.             $this->tracer->get(self::buildName($productId)),
  77.             $this->extractStreamTags($response),
  78.             $this->extractProductIds($response),
  79.             [self::buildName($productId)]
  80.         );
  81.         $event = new CrossSellingRouteCacheTagsEvent($productId$tags$request$response$context$criteria);
  82.         $this->dispatcher->dispatch($event);
  83.         return array_unique(array_filter($event->getTags()));
  84.     }
  85.     /**
  86.      * @return array<string>
  87.      */
  88.     private function extractStreamTags(ProductCrossSellingRouteResponse $response): array
  89.     {
  90.         $ids = [];
  91.         foreach ($response->getResult() as $element) {
  92.             $ids[] = $element->getStreamId();
  93.         }
  94.         $ids array_unique(array_filter($ids));
  95.         return array_map(EntityCacheKeyGenerator::buildStreamTag(...), $ids);
  96.     }
  97.     /**
  98.      * @return array<string>
  99.      */
  100.     private function extractProductIds(ProductCrossSellingRouteResponse $response): array
  101.     {
  102.         $ids = [];
  103.         foreach ($response->getResult() as $element) {
  104.             $ids = [...$ids, ...$element->getProducts()->getIds()];
  105.         }
  106.         $ids array_unique(array_filter($ids));
  107.         return array_map(EntityCacheKeyGenerator::buildProductTag(...), $ids);
  108.     }
  109. }