<?php
namespace App\EventSubscriber;
use App\Entity\Category;
use App\Service\CatalogService;
use App\Service\ModuleService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class CatalogSubscriber implements EventSubscriberInterface
{
private Environment $twig;
private EntityManagerInterface $em;
private ModuleService $moduleService;
private CatalogService $catalogService;
public function __construct(
Environment $twig,
EntityManagerInterface $em,
ModuleService $moduleService,
CatalogService $catalogService
) {
$this->twig = $twig;
$this->moduleService = $moduleService;
$this->em = $em;
$this->catalogService = $catalogService;
}
public function onKernelController(ControllerEvent $event): void
{
$tree_catalog = array();
if ($this->moduleService->access('catalog') or $this->moduleService->access('catalog_wallet', 'command')) {
/** @var Category[] $categories */
$categories = $this->em->getRepository(Category::class)->getRootNodes('position');
foreach ($categories as $category) {
$sub_tree = $this->getSubTree($category);
if ($sub_tree !== false) {
$tree_catalog[] = $sub_tree;
}
}
}
$this->twig->addGlobal('tree_catalog', $tree_catalog);
}
/**
* @param Category $category
* @return array|bool
*/
private function getSubTree(Category $category): bool|array
{
$tree = [];
$tree['object'] = $category;
$tree['children'] = array();
$isValid = $this->catalogService->isCategoryValid($category);
if ($category->hasChildren()) {
foreach ($category->getChildren() as $category_child) {
$tree_child = $this->getSubTree($category_child);
if ($tree_child !== false) {
$tree['children'][] = $tree_child;
$isValid = true;
}
}
}
if (!$isValid) {
return false;
}
return $tree;
}
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::CONTROLLER => 'onKernelController',
);
}
}