vendor/shopware/core/Content/Category/SalesChannel/NavigationRoute.php line 125

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Category\SalesChannel;
  3. use Doctrine\DBAL\Connection;
  4. use OpenApi\Annotations as OA;
  5. use Shopware\Core\Content\Category\CategoryCollection;
  6. use Shopware\Core\Content\Category\CategoryEntity;
  7. use Shopware\Core\Content\Category\Exception\CategoryNotFoundException;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\FetchModeHelper;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\TermsAggregation;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\CountAggregation;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\AggregationResult\Bucket\TermsResult;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\RangeFilter;
  16. use Shopware\Core\Framework\Plugin\Exception\DecorationPatternException;
  17. use Shopware\Core\Framework\Routing\Annotation\Entity;
  18. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  19. use Shopware\Core\Framework\Routing\Annotation\Since;
  20. use Shopware\Core\Framework\Uuid\Uuid;
  21. use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
  22. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\Routing\Annotation\Route;
  25. /**
  26.  * @RouteScope(scopes={"store-api"})
  27.  */
  28. class NavigationRoute extends AbstractNavigationRoute
  29. {
  30.     /**
  31.      * @var SalesChannelRepositoryInterface
  32.      */
  33.     private $categoryRepository;
  34.     /**
  35.      * @var Connection
  36.      */
  37.     private $connection;
  38.     public function __construct(
  39.         Connection $connection,
  40.         SalesChannelRepositoryInterface $repository
  41.     ) {
  42.         $this->categoryRepository $repository;
  43.         $this->connection $connection;
  44.     }
  45.     public function getDecorated(): AbstractNavigationRoute
  46.     {
  47.         throw new DecorationPatternException(self::class);
  48.     }
  49.     /**
  50.      * @Since("6.2.0.0")
  51.      * @Entity("category")
  52.      * @OA\Post(
  53.      *      path="/navigation/{requestActiveId}/{requestRootId}",
  54.      *      summary="Fetch a navigation menu",
  55.      *      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.
  56. 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.
  57. * main-navigation
  58. * service-navigation
  59. * footer-navigation",
  60.      *      operationId="readNavigation",
  61.      *      tags={"Store API", "Category"},
  62.      *      @OA\Parameter(name="Api-Basic-Parameters"),
  63.      *      @OA\Parameter(
  64.      *          name="sw-include-seo-urls",
  65.      *          description="Instructs Shopware to try and resolve SEO URLs for the given navigation item",
  66.      *          @OA\Schema(type="boolean"),
  67.      *          in="header",
  68.      *          required=false
  69.      *      ),
  70.      *      @OA\Parameter(
  71.      *          name="requestActiveId",
  72.      *          description="Identifier of the active category in the navigation tree (if not used, just set to the same as rootId).",
  73.      *          @OA\Schema(type="string", pattern="^[0-9a-f]{32}$"),
  74.      *          in="path",
  75.      *          required=true
  76.      *      ),
  77.      *      @OA\Parameter(
  78.      *          name="requestRootId",
  79.      *          description="Identifier of the root category for your desired navigation tree. You can use it to fetch sub-trees of your navigation tree.",
  80.      *          @OA\Schema(type="string", pattern="^[0-9a-f]{32}$"),
  81.      *          in="path",
  82.      *          required=true
  83.      *      ),
  84.      *      @OA\RequestBody(
  85.      *          required=true,
  86.      *          @OA\JsonContent(
  87.      *              @OA\Property(
  88.      *                  property="depth",
  89.      *                  description="Determines the depth of fetched navigation levels.",
  90.      *                  @OA\Schema(type="integer", default="2")
  91.      *              ),
  92.      *              @OA\Property(
  93.      *                  property="buildTree",
  94.      *                  description="Return the categories as a tree or as a flat list.",
  95.      *                  @OA\Schema(type="boolean", default="true")
  96.      *              )
  97.      *          )
  98.      *      ),
  99.      *      @OA\Response(
  100.      *          response="200",
  101.      *          description="All available navigations",
  102.      *          @OA\JsonContent(ref="#/components/schemas/NavigationRouteResponse")
  103.      *     )
  104.      * )
  105.      * @Route("/store-api/navigation/{activeId}/{rootId}", name="store-api.navigation", methods={"GET", "POST"})
  106.      */
  107.     public function load(
  108.         string $activeId,
  109.         string $rootId,
  110.         Request $request,
  111.         SalesChannelContext $context,
  112.         Criteria $criteria
  113.     ): NavigationRouteResponse {
  114.         $depth $request->query->getInt('depth'$request->request->getInt('depth'2));
  115.         $metaInfo $this->getCategoryMetaInfo($activeId$rootId);
  116.         $active $this->getMetaInfoById($activeId$metaInfo);
  117.         $root $this->getMetaInfoById($rootId$metaInfo);
  118.         // Validate the provided category is part of the sales channel
  119.         $this->validate($activeId$active['path'], $context);
  120.         $isChild $this->isChildCategory($activeId$active['path'], $rootId);
  121.         // If the provided activeId is not part of the rootId, a fallback to the rootId must be made here.
  122.         // The passed activeId is therefore part of another navigation and must therefore not be loaded.
  123.         // The availability validation has already been done in the `validate` function.
  124.         if (!$isChild) {
  125.             $activeId $rootId;
  126.         }
  127.         $categories = new CategoryCollection();
  128.         if ($depth 0) {
  129.             // Load the first two levels without using the activeId in the query
  130.             $categories $this->loadLevels($rootId, (int) $root['level'], $context, clone $criteria$depth);
  131.         }
  132.         // If the active category is part of the provided root id, we have to load the children and the parents of the active id
  133.         $categories $this->loadChildren($activeId$context$rootId$metaInfo$categories, clone $criteria);
  134.         return new NavigationRouteResponse($categories);
  135.     }
  136.     private function loadCategories(array $idsSalesChannelContext $contextCriteria $criteria): CategoryCollection
  137.     {
  138.         $criteria->setIds($ids);
  139.         $criteria->addAssociation('media');
  140.         $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_NONE);
  141.         /** @var CategoryCollection $missing */
  142.         $missing $this->categoryRepository->search($criteria$context)->getEntities();
  143.         return $missing;
  144.     }
  145.     private function loadLevels(string $rootIdint $rootLevelSalesChannelContext $contextCriteria $criteriaint $depth 2): CategoryCollection
  146.     {
  147.         $criteria->addFilter(
  148.             new ContainsFilter('path''|' $rootId '|'),
  149.             new RangeFilter('level', [
  150.                 RangeFilter::GT => $rootLevel,
  151.                 RangeFilter::LTE => $rootLevel $depth,
  152.             ])
  153.         );
  154.         $criteria->addAssociation('media');
  155.         $criteria->setLimit(null);
  156.         $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_NONE);
  157.         /** @var CategoryCollection $levels */
  158.         $levels $this->categoryRepository->search($criteria$context)->getEntities();
  159.         // Count visible children that are already included in the original query
  160.         foreach ($levels as $level) {
  161.             $count $levels->filter(function (CategoryEntity $category) use ($level) {
  162.                 return $category->getParentId() === $level->getId() && $category->getVisible() && $category->getActive();
  163.             })->count();
  164.             $level->setVisibleChildCount($count);
  165.         }
  166.         // Fetch additional level of categories for counting visible children that are NOT included in the original query
  167.         $criteria = new Criteria();
  168.         $criteria->addFilter(
  169.             new ContainsFilter('path''|' $rootId '|'),
  170.             new EqualsFilter('level'$rootLevel $depth 1),
  171.             new EqualsFilter('active'true),
  172.             new EqualsFilter('visible'true)
  173.         );
  174.         $criteria->addAggregation(
  175.             new TermsAggregation('category-ids''parentId'nullnull, new CountAggregation('visible-children-count''id'))
  176.         );
  177.         $termsResult $this->categoryRepository
  178.             ->aggregate($criteria$context)
  179.             ->get('category-ids');
  180.         if ($termsResult instanceof TermsResult) {
  181.             foreach ($termsResult->getBuckets() as $bucket) {
  182.                 $key $bucket->getKey();
  183.                 if ($key === null) {
  184.                     continue;
  185.                 }
  186.                 $parent $levels->get($key);
  187.                 if ($parent instanceof CategoryEntity) {
  188.                     $parent->setVisibleChildCount($bucket->getCount());
  189.                 }
  190.             }
  191.         }
  192.         return $levels;
  193.     }
  194.     private function getCategoryMetaInfo(string $activeIdstring $rootId): array
  195.     {
  196.         $result $this->connection->fetchAllAssociative('
  197.             # navigation-route::meta-information
  198.             SELECT LOWER(HEX(`id`)), `path`, `level`
  199.             FROM `category`
  200.             WHERE `id` = :activeId OR `parent_id` = :activeId OR `id` = :rootId
  201.         ', ['activeId' => Uuid::fromHexToBytes($activeId), 'rootId' => Uuid::fromHexToBytes($rootId)]);
  202.         if (!$result) {
  203.             throw new CategoryNotFoundException($activeId);
  204.         }
  205.         return FetchModeHelper::groupUnique($result);
  206.     }
  207.     private function getMetaInfoById(string $id, array $metaInfo): array
  208.     {
  209.         if (!\array_key_exists($id$metaInfo)) {
  210.             throw new CategoryNotFoundException($id);
  211.         }
  212.         return $metaInfo[$id];
  213.     }
  214.     private function loadChildren(string $activeIdSalesChannelContext $contextstring $rootId, array $metaInfoCategoryCollection $categoriesCriteria $criteria): CategoryCollection
  215.     {
  216.         $active $this->getMetaInfoById($activeId$metaInfo);
  217.         unset($metaInfo[$rootId], $metaInfo[$activeId]);
  218.         $childIds array_keys($metaInfo);
  219.         // Fetch all parents and first-level children of the active category, if they're not already fetched
  220.         $missing $this->getMissingIds($activeId$active['path'], $childIds$categories);
  221.         if (empty($missing)) {
  222.             return $categories;
  223.         }
  224.         $categories->merge(
  225.             $this->loadCategories($missing$context$criteria)
  226.         );
  227.         return $categories;
  228.     }
  229.     private function getMissingIds(string $activeId, ?string $path, array $childIdsCategoryCollection $alreadyLoaded): array
  230.     {
  231.         $parentIds array_filter(explode('|'$path ?? ''));
  232.         $haveToBeIncluded array_merge($childIds$parentIds, [$activeId]);
  233.         $included $alreadyLoaded->getIds();
  234.         $included array_flip($included);
  235.         return array_diff($haveToBeIncluded$included);
  236.     }
  237.     private function validate(string $activeId, ?string $pathSalesChannelContext $context): void
  238.     {
  239.         $ids array_filter([
  240.             $context->getSalesChannel()->getFooterCategoryId(),
  241.             $context->getSalesChannel()->getServiceCategoryId(),
  242.             $context->getSalesChannel()->getNavigationCategoryId(),
  243.         ]);
  244.         foreach ($ids as $id) {
  245.             if ($this->isChildCategory($activeId$path$id)) {
  246.                 return;
  247.             }
  248.         }
  249.         throw new CategoryNotFoundException($activeId);
  250.     }
  251.     private function isChildCategory(string $activeId, ?string $pathstring $rootId): bool
  252.     {
  253.         if ($rootId === $activeId) {
  254.             return true;
  255.         }
  256.         if ($path === null) {
  257.             return false;
  258.         }
  259.         if (mb_strpos($path'|' $rootId '|') !== false) {
  260.             return true;
  261.         }
  262.         return false;
  263.     }
  264. }