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

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