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

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