<?phpdeclare(strict_types=1);namespace App\Subscriber;use App\Module\Catalog\Provider\CategoryTreeProvider;use Denios\Data\Product\Product;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpKernel\Event\ViewEvent;use Symfony\Component\HttpKernel\KernelEvents;use function array_reverse;/** * Class BreadcrumbSubscriber * * @author André Varelmann <andre.varelmann@bestit-online.de> * @package App\Subscriber */class BreadcrumbSubscriber implements EventSubscriberInterface{ /** * @var PAGE_TYPE_CMS_CONTENT Const for the name of $controllerResult type for cms results */ private const PAGE_TYPE_CMS_CONTENT = 'cmsContent'; /** * @var PAGE_TYPE_PRODUCT Const for the name of $controllerResult type for product results */ private const PAGE_TYPE_PRODUCT = 'product'; /** * @var PAGE_TYPE_CATEGORY_CONTENT Const for the name of $controllerResult type for category results */ private const PAGE_TYPE_CATEGORY_CONTENT = 'categoryContent'; /** * @var CategoryTreeProvider */ private $provider; /** * BreadcrumbSubscriber constructor. * * @param CategoryTreeProvider $provider */ public function __construct(CategoryTreeProvider $provider) { $this->provider = $provider; } /** * Returns an array of event names this subscriber wants to listen to. * * @return array The event names to listen to */ public static function getSubscribedEvents(): array { return [KernelEvents::VIEW => 'onKernelResponse']; } /** * @param ViewEvent $event * * @return void */ public function onKernelResponse(ViewEvent $event): void { $controllerResult = $event->getControllerResult(); if (is_array($controllerResult)) { if (isset($controllerResult[self::PAGE_TYPE_CMS_CONTENT])) { $controllerResult['breadcrumbs'] = $this->getBreadcrumbs($controllerResult[self::PAGE_TYPE_CMS_CONTENT]->uuid); } if (isset($controllerResult[self::PAGE_TYPE_CATEGORY_CONTENT])) { $controllerResult['breadcrumbs'] = $this->getBreadcrumbs($controllerResult[self::PAGE_TYPE_CATEGORY_CONTENT]['id']); } if (isset($controllerResult[self::PAGE_TYPE_PRODUCT]) && $controllerResult[self::PAGE_TYPE_PRODUCT] instanceof Product) { $firstCategoryId = current($controllerResult[self::PAGE_TYPE_PRODUCT]->categories); $controllerResult['breadcrumbs'] = $this->getBreadcrumbs($firstCategoryId); } } $event->setControllerResult($controllerResult); } /** * * @return array */ private function getBreadcrumbs($categoryId): array { $categories = $this->provider->getFlat(); $breadcrumbs = []; while (isset($categories[$categoryId])) { $category = $categories[$categoryId]; $breadcrumb = [ 'name' => $category['name'] ]; if (($category['isActive'] ?? true ) and ($category['inNavigation'] ?? true )) { $breadcrumb['link'] = $category['slug']; $breadcrumb['branch'] = $category['branch'] ?? 'cp'; } $breadcrumbs[] = $breadcrumb; $categoryId = $category['parent']; } return array_reverse($breadcrumbs); }}