vendor/shopware/core/Content/Category/SalesChannel/CachedNavigationRoute.php line 140

Open in your IDE?
  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\FieldSerializer\JsonFieldSerializer;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  13. use Shopware\Core\Framework\Routing\Annotation\Entity;
  14. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  15. use Shopware\Core\Framework\Routing\Annotation\Since;
  16. use Shopware\Core\Profiling\Profiler;
  17. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  18. use Shopware\Core\System\SalesChannel\StoreApiResponse;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Symfony\Contracts\Cache\CacheInterface;
  22. use Symfony\Contracts\Cache\ItemInterface;
  23. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  24. /**
  25.  * @Route(defaults={"_routeScope"={"store-api"}})
  26.  */
  27. class CachedNavigationRoute extends AbstractNavigationRoute
  28. {
  29.     public const ALL_TAG 'navigation';
  30.     public const BASE_NAVIGATION_TAG 'base-navigation';
  31.     private AbstractNavigationRoute $decorated;
  32.     private CacheInterface $cache;
  33.     private EntityCacheKeyGenerator $generator;
  34.     /**
  35.      * @var AbstractCacheTracer<NavigationRouteResponse>
  36.      */
  37.     private AbstractCacheTracer $tracer;
  38.     /**
  39.      * @var array<string>
  40.      */
  41.     private array $states;
  42.     private EventDispatcherInterface $dispatcher;
  43.     /**
  44.      * @internal
  45.      *
  46.      * @param AbstractCacheTracer<NavigationRouteResponse> $tracer
  47.      * @param array<string> $states
  48.      */
  49.     public function __construct(
  50.         AbstractNavigationRoute $decorated,
  51.         CacheInterface $cache,
  52.         EntityCacheKeyGenerator $generator,
  53.         AbstractCacheTracer $tracer,
  54.         EventDispatcherInterface $dispatcher,
  55.         array $states
  56.     ) {
  57.         $this->decorated $decorated;
  58.         $this->cache $cache;
  59.         $this->generator $generator;
  60.         $this->tracer $tracer;
  61.         $this->states $states;
  62.         $this->dispatcher $dispatcher;
  63.     }
  64.     public function getDecorated(): AbstractNavigationRoute
  65.     {
  66.         return $this->decorated;
  67.     }
  68.     /**
  69.      * @Since("6.2.0.0")
  70.      * @Entity("category")
  71.      * @Route("/store-api/navigation/{activeId}/{rootId}", name="store-api.navigation", methods={"GET", "POST"})
  72.      */
  73.     public function load(string $activeIdstring $rootIdRequest $requestSalesChannelContext $contextCriteria $criteria): NavigationRouteResponse
  74.     {
  75.         return Profiler::trace('navigation-route', function () use ($activeId$rootId$request$context$criteria) {
  76.             if ($context->hasState(...$this->states)) {
  77.                 return $this->getDecorated()->load($activeId$rootId$request$context$criteria);
  78.             }
  79.             $depth $request->query->getInt('depth'$request->request->getInt('depth'2));
  80.             // first we load the base navigation, the base navigation is shared for all storefront listings
  81.             $response $this->loadNavigation($request$rootId$rootId$depth$context$criteria, [self::ALL_TAGself::BASE_NAVIGATION_TAG]);
  82.             // no we have to check if the active category is loaded and the children of the active category are loaded
  83.             if ($this->isActiveLoaded($rootId$response->getCategories(), $activeId)) {
  84.                 return $response;
  85.             }
  86.             // reload missing children of active category, depth 0 allows us the skip base navigation loading in the core route
  87.             $active $this->loadNavigation($request$activeId$rootId0$context$criteria, [self::ALL_TAG]);
  88.             $response->getCategories()->merge($active->getCategories());
  89.             return $response;
  90.         });
  91.     }
  92.     public static function buildName(string $id): string
  93.     {
  94.         return 'navigation-route-' $id;
  95.     }
  96.     /**
  97.      * @param array<string> $tags
  98.      */
  99.     private function loadNavigation(Request $requeststring $activestring $rootIdint $depthSalesChannelContext $contextCriteria $criteria, array $tags = []): NavigationRouteResponse
  100.     {
  101.         $key $this->generateKey($active$rootId$depth$request$context$criteria);
  102.         if ($key === null) {
  103.             return $this->getDecorated()->load($active$rootId$request$context$criteria);
  104.         }
  105.         $value $this->cache->get($key, function (ItemInterface $item) use ($active$depth$rootId$request$context$criteria$tags) {
  106.             $request->query->set('depth', (string) $depth);
  107.             $name self::buildName($active);
  108.             $response $this->tracer->trace($name, function () use ($active$rootId$request$context$criteria) {
  109.                 return $this->getDecorated()->load($active$rootId$request$context$criteria);
  110.             });
  111.             $item->tag($this->generateTags($tags$active$rootId$depth$request$response$context$criteria));
  112.             return CacheValueCompressor::compress($response);
  113.         });
  114.         return CacheValueCompressor::uncompress($value);
  115.     }
  116.     private function isActiveLoaded(string $rootCategoryCollection $categoriesstring $activeId): bool
  117.     {
  118.         if ($root === $activeId) {
  119.             return true;
  120.         }
  121.         $active $categories->get($activeId);
  122.         if (!$active instanceof CategoryEntity) {
  123.             return false;
  124.         }
  125.         if ($active->getChildCount() === && \is_string($active->getParentId())) {
  126.             return $categories->has($active->getParentId());
  127.         }
  128.         foreach ($categories as $category) {
  129.             if ($category->getParentId() === $activeId) {
  130.                 return true;
  131.             }
  132.         }
  133.         return false;
  134.     }
  135.     private function generateKey(string $activestring $rootIdint $depthRequest $requestSalesChannelContext $contextCriteria $criteria): ?string
  136.     {
  137.         $parts = [
  138.             $rootId,
  139.             $depth,
  140.             $this->generator->getCriteriaHash($criteria),
  141.             $this->generator->getSalesChannelContextHash($context, [RuleAreas::CATEGORY_AREA]),
  142.         ];
  143.         $event = new NavigationRouteCacheKeyEvent($parts$active$rootId$depth$request$context$criteria);
  144.         $this->dispatcher->dispatch($event);
  145.         if (!$event->shouldCache()) {
  146.             return null;
  147.         }
  148.         return self::buildName($active) . '-' md5(JsonFieldSerializer::encodeJson($event->getParts()));
  149.     }
  150.     /**
  151.      * @param array<string> $tags
  152.      *
  153.      * @return array<string>
  154.      */
  155.     private function generateTags(array $tagsstring $activestring $rootIdint $depthRequest $requestStoreApiResponse $responseSalesChannelContext $contextCriteria $criteria): array
  156.     {
  157.         $tags array_merge(
  158.             $tags,
  159.             $this->tracer->get(self::buildName($context->getSalesChannelId())),
  160.             [self::buildName($context->getSalesChannelId())]
  161.         );
  162.         $event = new NavigationRouteCacheTagsEvent($tags$active$rootId$depth$request$response$context$criteria);
  163.         $this->dispatcher->dispatch($event);
  164.         return array_unique(array_filter($event->getTags()));
  165.     }
  166. }