src/Core/Framework/Adapter/Twig/Extension/BuildBreadcrumbExtension.php line 62

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\Adapter\Twig\Extension;
  3. use Shopware\Core\Content\Category\CategoryCollection;
  4. use Shopware\Core\Content\Category\CategoryEntity;
  5. use Shopware\Core\Content\Category\Service\CategoryBreadcrumbBuilder;
  6. use Shopware\Core\Framework\Context;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  9. use Shopware\Core\Framework\Log\Package;
  10. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  11. use Twig\Extension\AbstractExtension;
  12. use Twig\TwigFunction;
  13. #[Package('core')]
  14. class BuildBreadcrumbExtension extends AbstractExtension
  15. {
  16.     /**
  17.      * @internal
  18.      */
  19.     public function __construct(
  20.         private readonly CategoryBreadcrumbBuilder $categoryBreadcrumbBuilder,
  21.         private readonly EntityRepository $categoryRepository
  22.     ) {
  23.     }
  24.     public function getFunctions(): array
  25.     {
  26.         return [
  27.             new TwigFunction('sw_breadcrumb_full'$this->getFullBreadcrumb(...), ['needs_context' => true]),
  28.         ];
  29.     }
  30.     /**
  31.      * @param array<string, mixed> $twigContext
  32.      *
  33.      * @return array<string, CategoryEntity>
  34.      */
  35.     public function getFullBreadcrumb(array $twigContextCategoryEntity $categoryContext $context): array
  36.     {
  37.         $salesChannel null;
  38.         if (\array_key_exists('context'$twigContext) && $twigContext['context'] instanceof SalesChannelContext) {
  39.             $salesChannel $twigContext['context']->getSalesChannel();
  40.         }
  41.         $seoBreadcrumb $this->categoryBreadcrumbBuilder->build($category$salesChannel);
  42.         if ($seoBreadcrumb === null) {
  43.             return [];
  44.         }
  45.         /** @var list<string> $categoryIds */
  46.         $categoryIds array_keys($seoBreadcrumb);
  47.         if (empty($categoryIds)) {
  48.             return [];
  49.         }
  50.         $criteria = new Criteria($categoryIds);
  51.         $criteria->setTitle('breadcrumb-extension');
  52.         /** @var CategoryCollection $categories */
  53.         $categories $this->categoryRepository->search($criteria$context)->getEntities();
  54.         $breadcrumb = [];
  55.         foreach ($categoryIds as $categoryId) {
  56.             if ($categories->get($categoryId) === null) {
  57.                 continue;
  58.             }
  59.             $breadcrumb[$categoryId] = $categories->get($categoryId);
  60.         }
  61.         return $breadcrumb;
  62.     }
  63. }