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

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Category\SalesChannel;
  3. use OpenApi\Annotations as OA;
  4. use Shopware\Core\Content\Category\CategoryCollection;
  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\FieldSerializer\JsonFieldSerializer;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  12. use Shopware\Core\Framework\Routing\Annotation\Entity;
  13. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  14. use Shopware\Core\Framework\Routing\Annotation\Since;
  15. use Shopware\Core\Profiling\Profiler;
  16. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  17. use Shopware\Core\System\SalesChannel\StoreApiResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Contracts\Cache\CacheInterface;
  21. use Symfony\Contracts\Cache\ItemInterface;
  22. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  23. /**
  24.  * @Route(defaults={"_routeScope"={"store-api"}})
  25.  */
  26. class CachedNavigationRoute extends AbstractNavigationRoute
  27. {
  28.     public const ALL_TAG 'navigation';
  29.     public const BASE_NAVIGATION_TAG 'base-navigation';
  30.     private AbstractNavigationRoute $decorated;
  31.     private CacheInterface $cache;
  32.     private EntityCacheKeyGenerator $generator;
  33.     /**
  34.      * @var AbstractCacheTracer<NavigationRouteResponse>
  35.      */
  36.     private AbstractCacheTracer $tracer;
  37.     private array $states;
  38.     private EventDispatcherInterface $dispatcher;
  39.     /**
  40.      * @internal
  41.      *
  42.      * @param AbstractCacheTracer<NavigationRouteResponse> $tracer
  43.      */
  44.     public function __construct(
  45.         AbstractNavigationRoute $decorated,
  46.         CacheInterface $cache,
  47.         EntityCacheKeyGenerator $generator,
  48.         AbstractCacheTracer $tracer,
  49.         EventDispatcherInterface $dispatcher,
  50.         array $states
  51.     ) {
  52.         $this->decorated $decorated;
  53.         $this->cache $cache;
  54.         $this->generator $generator;
  55.         $this->tracer $tracer;
  56.         $this->states $states;
  57.         $this->dispatcher $dispatcher;
  58.     }
  59.     public function getDecorated(): AbstractNavigationRoute
  60.     {
  61.         return $this->decorated;
  62.     }
  63.     /**
  64.      * @Since("6.2.0.0")
  65.      * @Entity("category")
  66.      * @OA\Post(
  67.      *      path="/navigation/{requestActiveId}/{requestRootId}",
  68.      *      summary="Fetch a navigation menu",
  69.      *      description="This endpoint returns categories that can be used as a page navigation. You can either return them as a tree or as a flat list. You can also control the depth of the tree.
  70. Instead of passing uuids, you can also use one of the following aliases for the activeId and rootId parameters to get the respective navigations of your sales channel.
  71. * main-navigation
  72. * service-navigation
  73. * footer-navigation",
  74.      *      operationId="readNavigation",
  75.      *      tags={"Store API", "Category"},
  76.      *      @OA\Parameter(name="Api-Basic-Parameters"),
  77.      *      @OA\Parameter(
  78.      *          name="sw-include-seo-urls",
  79.      *          description="Instructs Shopware to try and resolve SEO URLs for the given navigation item",
  80.      *          @OA\Schema(type="boolean"),
  81.      *          in="header",
  82.      *          required=false
  83.      *      ),
  84.      *      @OA\Parameter(
  85.      *          name="requestActiveId",
  86.      *          description="Identifier of the active category in the navigation tree (if not used, just set to the same as rootId).",
  87.      *          @OA\Schema(type="string", pattern="^[0-9a-f]{32}$"),
  88.      *          in="path",
  89.      *          required=true
  90.      *      ),
  91.      *      @OA\Parameter(
  92.      *          name="requestRootId",
  93.      *          description="Identifier of the root category for your desired navigation tree. You can use it to fetch sub-trees of your navigation tree.",
  94.      *          @OA\Schema(type="string", pattern="^[0-9a-f]{32}$"),
  95.      *          in="path",
  96.      *          required=true
  97.      *      ),
  98.      *      @OA\RequestBody(
  99.      *          required=true,
  100.      *          @OA\JsonContent(
  101.      *              @OA\Property(
  102.      *                  property="depth",
  103.      *                  description="Determines the depth of fetched navigation levels.",
  104.      *                  @OA\Schema(type="integer", default="2")
  105.      *              ),
  106.      *              @OA\Property(
  107.      *                  property="buildTree",
  108.      *                  description="Return the categories as a tree or as a flat list.",
  109.      *                  @OA\Schema(type="boolean", default="true")
  110.      *              )
  111.      *          )
  112.      *      ),
  113.      *      @OA\Response(
  114.      *          response="200",
  115.      *          description="All available navigations",
  116.      *          @OA\JsonContent(ref="#/components/schemas/NavigationRouteResponse")
  117.      *     )
  118.      * )
  119.      * @Route("/store-api/navigation/{activeId}/{rootId}", name="store-api.navigation", methods={"GET", "POST"})
  120.      */
  121.     public function load(string $activeIdstring $rootIdRequest $requestSalesChannelContext $contextCriteria $criteria): NavigationRouteResponse
  122.     {
  123.         return Profiler::trace('navigation-route', function () use ($activeId$rootId$request$context$criteria) {
  124.             if ($context->hasState(...$this->states)) {
  125.                 return $this->getDecorated()->load($activeId$rootId$request$context$criteria);
  126.             }
  127.             $depth $request->query->getInt('depth'$request->request->getInt('depth'2));
  128.             // first we load the base navigation, the base navigation is shared for all storefront listings
  129.             $response $this->loadNavigation($request$rootId$rootId$depth$context$criteria, [self::ALL_TAGself::BASE_NAVIGATION_TAG]);
  130.             // no we have to check if the active category is loaded and the children of the active category are loaded
  131.             if ($this->isActiveLoaded($rootId$response->getCategories(), $activeId)) {
  132.                 return $response;
  133.             }
  134.             // reload missing children of active category, depth 0 allows us the skip base navigation loading in the core route
  135.             $active $this->loadNavigation($request$activeId$rootId0$context$criteria, [self::ALL_TAG]);
  136.             $response->getCategories()->merge($active->getCategories());
  137.             return $response;
  138.         });
  139.     }
  140.     public static function buildName(string $id): string
  141.     {
  142.         return 'navigation-route-' $id;
  143.     }
  144.     private function loadNavigation(Request $requeststring $activestring $rootIdint $depthSalesChannelContext $contextCriteria $criteria, array $tags = []): NavigationRouteResponse
  145.     {
  146.         $key $this->generateKey($active$rootId$depth$request$context$criteria);
  147.         $value $this->cache->get($key, function (ItemInterface $item) use ($active$depth$rootId$request$context$criteria$tags) {
  148.             $request->query->set('depth', (string) $depth);
  149.             $name self::buildName($active);
  150.             $response $this->tracer->trace($name, function () use ($active$rootId$request$context$criteria) {
  151.                 return $this->getDecorated()->load($active$rootId$request$context$criteria);
  152.             });
  153.             $item->tag($this->generateTags($tags$active$rootId$depth$request$response$context$criteria));
  154.             return CacheValueCompressor::compress($response);
  155.         });
  156.         return CacheValueCompressor::uncompress($value);
  157.     }
  158.     private function isActiveLoaded(string $rootCategoryCollection $categoriesstring $activeId): bool
  159.     {
  160.         if ($root === $activeId) {
  161.             return true;
  162.         }
  163.         $active $categories->get($activeId);
  164.         if ($active === null) {
  165.             return false;
  166.         }
  167.         if ($active->getChildCount() === 0) {
  168.             return $categories->has($active->getParentId());
  169.         }
  170.         foreach ($categories as $category) {
  171.             if ($category->getParentId() === $activeId) {
  172.                 return true;
  173.             }
  174.         }
  175.         return false;
  176.     }
  177.     private function generateKey(string $activestring $rootIdint $depthRequest $requestSalesChannelContext $contextCriteria $criteria): string
  178.     {
  179.         $parts = [
  180.             $rootId,
  181.             $depth,
  182.             $this->generator->getCriteriaHash($criteria),
  183.             $this->generator->getSalesChannelContextHash($context),
  184.         ];
  185.         $event = new NavigationRouteCacheKeyEvent($parts$active$rootId$depth$request$context$criteria);
  186.         $this->dispatcher->dispatch($event);
  187.         return self::buildName($active) . '-' md5(JsonFieldSerializer::encodeJson($event->getParts()));
  188.     }
  189.     private function generateTags(array $tagsstring $activestring $rootIdint $depthRequest $requestStoreApiResponse $responseSalesChannelContext $contextCriteria $criteria): array
  190.     {
  191.         $tags array_merge(
  192.             $tags,
  193.             $this->tracer->get(self::buildName($context->getSalesChannelId())),
  194.             [self::buildName($context->getSalesChannelId())]
  195.         );
  196.         $event = new NavigationRouteCacheTagsEvent($tags$active$rootId$depth$request$response$context$criteria);
  197.         $this->dispatcher->dispatch($event);
  198.         return array_unique(array_filter($event->getTags()));
  199.     }
  200. }