src/Core/Content/Category/SalesChannel/CachedNavigationRoute.php line 51

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Category\SalesChannel;
  3. use Shopware\Core\Content\Category\CategoryCollection;
  4. use Shopware\Core\Content\Category\CategoryEntity;
  5. use Shopware\Core\Content\Category\Event\NavigationRouteCacheKeyEvent;
  6. use Shopware\Core\Content\Category\Event\NavigationRouteCacheTagsEvent;
  7. use Shopware\Core\Framework\Adapter\Cache\AbstractCacheTracer;
  8. use Shopware\Core\Framework\Adapter\Cache\CacheValueCompressor;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\RuleAreas;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  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 Shopware\Core\System\SalesChannel\StoreApiResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Contracts\Cache\CacheInterface;
  20. use Symfony\Contracts\Cache\ItemInterface;
  21. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  22. #[Route(defaults: ['_routeScope' => ['store-api']])]
  23. #[Package('content')]
  24. class CachedNavigationRoute extends AbstractNavigationRoute
  25. {
  26.     final public const ALL_TAG 'navigation';
  27.     final public const BASE_NAVIGATION_TAG 'base-navigation';
  28.     /**
  29.      * @internal
  30.      *
  31.      * @param AbstractCacheTracer<NavigationRouteResponse> $tracer
  32.      * @param array<string> $states
  33.      */
  34.     public function __construct(private readonly AbstractNavigationRoute $decorated, private readonly CacheInterface $cache, private readonly EntityCacheKeyGenerator $generator, private readonly AbstractCacheTracer $tracer, private readonly EventDispatcherInterface $dispatcher, private readonly array $states)
  35.     {
  36.     }
  37.     public function getDecorated(): AbstractNavigationRoute
  38.     {
  39.         return $this->decorated;
  40.     }
  41.     #[Route(path'/store-api/navigation/{activeId}/{rootId}'name'store-api.navigation'methods: ['GET''POST'], defaults: ['_entity' => 'category'])]
  42.     public function load(string $activeIdstring $rootIdRequest $requestSalesChannelContext $contextCriteria $criteria): NavigationRouteResponse
  43.     {
  44.         return Profiler::trace('navigation-route', function () use ($activeId$rootId$request$context$criteria) {
  45.             if ($context->hasState(...$this->states)) {
  46.                 return $this->getDecorated()->load($activeId$rootId$request$context$criteria);
  47.             }
  48.             $depth $request->query->getInt('depth'$request->request->getInt('depth'2));
  49.             // first we load the base navigation, the base navigation is shared for all storefront listings
  50.             $response $this->loadNavigation($request$rootId$rootId$depth$context$criteria, [self::ALL_TAGself::BASE_NAVIGATION_TAG]);
  51.             // no we have to check if the active category is loaded and the children of the active category are loaded
  52.             if ($this->isActiveLoaded($rootId$response->getCategories(), $activeId)) {
  53.                 return $response;
  54.             }
  55.             // reload missing children of active category, depth 0 allows us the skip base navigation loading in the core route
  56.             $active $this->loadNavigation($request$activeId$rootId0$context$criteria, [self::ALL_TAG]);
  57.             $response->getCategories()->merge($active->getCategories());
  58.             return $response;
  59.         });
  60.     }
  61.     public static function buildName(string $id): string
  62.     {
  63.         return 'navigation-route-' $id;
  64.     }
  65.     /**
  66.      * @param array<string> $tags
  67.      */
  68.     private function loadNavigation(Request $requeststring $activestring $rootIdint $depthSalesChannelContext $contextCriteria $criteria, array $tags = []): NavigationRouteResponse
  69.     {
  70.         $key $this->generateKey($active$rootId$depth$request$context$criteria);
  71.         if ($key === null) {
  72.             return $this->getDecorated()->load($active$rootId$request$context$criteria);
  73.         }
  74.         $value $this->cache->get($key, function (ItemInterface $item) use ($active$depth$rootId$request$context$criteria$tags) {
  75.             $request->query->set('depth', (string) $depth);
  76.             $name self::buildName($active);
  77.             $response $this->tracer->trace($name, fn () => $this->getDecorated()->load($active$rootId$request$context$criteria));
  78.             $item->tag($this->generateTags($tags$active$rootId$depth$request$response$context$criteria));
  79.             return CacheValueCompressor::compress($response);
  80.         });
  81.         return CacheValueCompressor::uncompress($value);
  82.     }
  83.     private function isActiveLoaded(string $rootCategoryCollection $categoriesstring $activeId): bool
  84.     {
  85.         if ($root === $activeId) {
  86.             return true;
  87.         }
  88.         $active $categories->get($activeId);
  89.         if (!$active instanceof CategoryEntity) {
  90.             return false;
  91.         }
  92.         if ($active->getChildCount() === && \is_string($active->getParentId())) {
  93.             return $categories->has($active->getParentId());
  94.         }
  95.         foreach ($categories as $category) {
  96.             if ($category->getParentId() === $activeId) {
  97.                 return true;
  98.             }
  99.         }
  100.         return false;
  101.     }
  102.     private function generateKey(string $activestring $rootIdint $depthRequest $requestSalesChannelContext $contextCriteria $criteria): ?string
  103.     {
  104.         $parts = [
  105.             $rootId,
  106.             $depth,
  107.             $this->generator->getCriteriaHash($criteria),
  108.             $this->generator->getSalesChannelContextHash($context, [RuleAreas::CATEGORY_AREA]),
  109.         ];
  110.         $event = new NavigationRouteCacheKeyEvent($parts$active$rootId$depth$request$context$criteria);
  111.         $this->dispatcher->dispatch($event);
  112.         if (!$event->shouldCache()) {
  113.             return null;
  114.         }
  115.         return self::buildName($active) . '-' md5(Json::encode($event->getParts()));
  116.     }
  117.     /**
  118.      * @param array<string> $tags
  119.      *
  120.      * @return array<string>
  121.      */
  122.     private function generateTags(array $tagsstring $activestring $rootIdint $depthRequest $requestStoreApiResponse $responseSalesChannelContext $contextCriteria $criteria): array
  123.     {
  124.         $tags array_merge(
  125.             $tags,
  126.             $this->tracer->get(self::buildName($context->getSalesChannelId())),
  127.             [self::buildName($context->getSalesChannelId())]
  128.         );
  129.         $event = new NavigationRouteCacheTagsEvent($tags$active$rootId$depth$request$response$context$criteria);
  130.         $this->dispatcher->dispatch($event);
  131.         return array_unique(array_filter($event->getTags()));
  132.     }
  133. }