src/Core/Content/Category/SalesChannel/CachedCategoryRoute.php line 62

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Category\SalesChannel;
  3. use Shopware\Core\Content\Category\Event\CategoryRouteCacheKeyEvent;
  4. use Shopware\Core\Content\Category\Event\CategoryRouteCacheTagsEvent;
  5. use Shopware\Core\Content\Cms\Aggregate\CmsSlot\CmsSlotEntity;
  6. use Shopware\Core\Content\Cms\SalesChannel\Struct\ProductBoxStruct;
  7. use Shopware\Core\Content\Cms\SalesChannel\Struct\ProductSliderStruct;
  8. use Shopware\Core\Framework\Adapter\Cache\AbstractCacheTracer;
  9. use Shopware\Core\Framework\Adapter\Cache\CacheValueCompressor;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\RuleAreas;
  12. use Shopware\Core\Framework\Log\Package;
  13. use Shopware\Core\Framework\Util\Json;
  14. use Shopware\Core\Profiling\Profiler;
  15. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Contracts\Cache\CacheInterface;
  19. use Symfony\Contracts\Cache\ItemInterface;
  20. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  21. #[Route(defaults: ['_routeScope' => ['store-api']])]
  22. #[Package('content')]
  23. class CachedCategoryRoute extends AbstractCategoryRoute
  24. {
  25.     /**
  26.      * @internal
  27.      *
  28.      * @param AbstractCacheTracer<CategoryRouteResponse> $tracer
  29.      * @param array<string> $states
  30.      */
  31.     public function __construct(private readonly AbstractCategoryRoute $decorated, private readonly CacheInterface $cache, private readonly EntityCacheKeyGenerator $generator, private readonly AbstractCacheTracer $tracer, private readonly EventDispatcherInterface $dispatcher, private readonly array $states)
  32.     {
  33.     }
  34.     public static function buildName(string $id): string
  35.     {
  36.         return 'category-route-' $id;
  37.     }
  38.     public function getDecorated(): AbstractCategoryRoute
  39.     {
  40.         return $this->decorated;
  41.     }
  42.     #[Route(path'/store-api/category/{navigationId}'name'store-api.category.detail'methods: ['GET''POST'])]
  43.     public function load(string $navigationIdRequest $requestSalesChannelContext $context): CategoryRouteResponse
  44.     {
  45.         return Profiler::trace('category-route', function () use ($navigationId$request$context) {
  46.             if ($context->hasState(...$this->states)) {
  47.                 return $this->getDecorated()->load($navigationId$request$context);
  48.             }
  49.             $key $this->generateKey($navigationId$request$context);
  50.             if ($key === null) {
  51.                 return $this->getDecorated()->load($navigationId$request$context);
  52.             }
  53.             $value $this->cache->get($key, function (ItemInterface $item) use ($navigationId$request$context) {
  54.                 $name self::buildName($navigationId);
  55.                 $response $this->tracer->trace($name, fn () => $this->getDecorated()->load($navigationId$request$context));
  56.                 $item->tag($this->generateTags($navigationId$response$request$context));
  57.                 return CacheValueCompressor::compress($response);
  58.             });
  59.             return CacheValueCompressor::uncompress($value);
  60.         });
  61.     }
  62.     private function generateKey(string $navigationIdRequest $requestSalesChannelContext $context): ?string
  63.     {
  64.         $parts = [...$request->query->all(), ...$request->request->all(), ...[$this->generator->getSalesChannelContextHash($context, [RuleAreas::CATEGORY_AREARuleAreas::PRODUCT_AREA])]];
  65.         $event = new CategoryRouteCacheKeyEvent($navigationId$parts$request$contextnull);
  66.         $this->dispatcher->dispatch($event);
  67.         if (!$event->shouldCache()) {
  68.             return null;
  69.         }
  70.         return self::buildName($navigationId) . '-' md5(Json::encode($event->getParts()));
  71.     }
  72.     /**
  73.      * @return array<string>
  74.      */
  75.     private function generateTags(string $navigationIdCategoryRouteResponse $responseRequest $requestSalesChannelContext $context): array
  76.     {
  77.         $tags array_merge(
  78.             $this->tracer->get(self::buildName($navigationId)),
  79.             $this->extractProductIds($response),
  80.             [self::buildName($navigationId)]
  81.         );
  82.         $event = new CategoryRouteCacheTagsEvent($navigationId$tags$request$response$contextnull);
  83.         $this->dispatcher->dispatch($event);
  84.         return array_unique(array_filter($event->getTags()));
  85.     }
  86.     /**
  87.      * @return array<string>
  88.      */
  89.     private function extractProductIds(CategoryRouteResponse $response): array
  90.     {
  91.         $page $response->getCategory()->getCmsPage();
  92.         if ($page === null) {
  93.             return [];
  94.         }
  95.         $ids = [];
  96.         $streamIds = [];
  97.         $slots $page->getElementsOfType('product-slider');
  98.         /** @var CmsSlotEntity $slot */
  99.         foreach ($slots as $slot) {
  100.             $slider $slot->getData();
  101.             if (!$slider instanceof ProductSliderStruct) {
  102.                 continue;
  103.             }
  104.             if ($slider->getStreamId() !== null) {
  105.                 $streamIds[] = $slider->getStreamId();
  106.             }
  107.             if ($slider->getProducts() === null) {
  108.                 continue;
  109.             }
  110.             foreach ($slider->getProducts() as $product) {
  111.                 $ids[] = $product->getId();
  112.                 $ids[] = $product->getParentId();
  113.             }
  114.         }
  115.         $slots $page->getElementsOfType('product-box');
  116.         /** @var CmsSlotEntity $slot */
  117.         foreach ($slots as $slot) {
  118.             $box $slot->getData();
  119.             if (!$box instanceof ProductBoxStruct) {
  120.                 continue;
  121.             }
  122.             if ($box->getProduct() === null) {
  123.                 continue;
  124.             }
  125.             $ids[] = $box->getProduct()->getId();
  126.             $ids[] = $box->getProduct()->getParentId();
  127.         }
  128.         $ids array_values(array_unique(array_filter($ids)));
  129.         return [...array_map(EntityCacheKeyGenerator::buildProductTag(...), $ids), ...array_map(EntityCacheKeyGenerator::buildStreamTag(...), $streamIds), ...[EntityCacheKeyGenerator::buildCmsTag($page->getId())]];
  130.     }
  131. }