src/EventSubscriber/CatalogSubscriber.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Category;
  4. use App\Service\CatalogService;
  5. use App\Service\ModuleService;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Twig\Environment;
  11. class CatalogSubscriber implements EventSubscriberInterface
  12. {
  13.     private Environment $twig;
  14.     private EntityManagerInterface $em;
  15.     private ModuleService $moduleService;
  16.     private CatalogService $catalogService;
  17.     public function __construct(
  18.         Environment $twig,
  19.         EntityManagerInterface $em,
  20.         ModuleService $moduleService,
  21.         CatalogService $catalogService
  22.     ) {
  23.         $this->twig $twig;
  24.         $this->moduleService $moduleService;
  25.         $this->em $em;
  26.         $this->catalogService $catalogService;
  27.     }
  28.     public function onKernelController(ControllerEvent $event): void
  29.     {
  30.         $tree_catalog = array();
  31.         if ($this->moduleService->access('catalog') or $this->moduleService->access('catalog_wallet''command')) {
  32.             /** @var Category[] $categories */
  33.             $categories $this->em->getRepository(Category::class)->getRootNodes('position');
  34.             foreach ($categories as $category) {
  35.                 $sub_tree $this->getSubTree($category);
  36.                 if ($sub_tree !== false) {
  37.                     $tree_catalog[] = $sub_tree;
  38.                 }
  39.             }
  40.         }
  41.         $this->twig->addGlobal('tree_catalog'$tree_catalog);
  42.     }
  43.     /**
  44.      * @param Category $category
  45.      * @return array|bool
  46.      */
  47.     private function getSubTree(Category $category): bool|array
  48.     {
  49.         $tree = [];
  50.         $tree['object'] = $category;
  51.         $tree['children'] = array();
  52.         $isValid $this->catalogService->isCategoryValid($category);
  53.         if ($category->hasChildren()) {
  54.             foreach ($category->getChildren() as $category_child) {
  55.                 $tree_child $this->getSubTree($category_child);
  56.                 if ($tree_child !== false) {
  57.                     $tree['children'][] = $tree_child;
  58.                     $isValid true;
  59.                 }
  60.             }
  61.         }
  62.         if (!$isValid) {
  63.             return false;
  64.         }
  65.         return $tree;
  66.     }
  67.     public static function getSubscribedEvents(): array
  68.     {
  69.         return array(
  70.             KernelEvents::CONTROLLER => 'onKernelController',
  71.         );
  72.     }
  73. }