*/ class NodeEventSubscriber extends EntityManagerEventSubscriber { protected NodeFactory $nodeFactory; protected EntityManager $entityManager; protected KernelInterface $kernel; protected Slugify $slugify; public function __construct( NodeFactory $nodeFactory, NodeRepository $nodeRepository, EntityManager $entityManager, KernelInterface $kernel, Slugify $slugify ) { $this->nodeFactory = $nodeFactory; $this->nodeRepository = $nodeRepository; $this->entityManager = $entityManager; $this->kernel = $kernel; $this->slugify = $slugify; } public function support(EntityInterface $entity) { return $entity instanceof Node; } public function onPreUpdate(EntityManagerEvent $event) { if (!$this->support($event->getEntity())) { return; } $node = $event->getEntity(); if ($node->getUrl()) { $generatedUrl = $node->getUrl(); } else { $path = []; $parent = $node->getParent(); if ($parent && $parent->getUrl()) { $pPath = trim($parent->getUrl(), '/'); if ($pPath) { $path[] = $pPath; } } $path[] = $this->slugify->slugify($node->getLabel()); $generatedUrl = '/'.implode('/', $path); } $urlExists = $this->nodeRepository->urlExists($generatedUrl, $node); if ($urlExists) { $number = 1; while ($this->nodeRepository->urlExists($generatedUrl.'-'.$number, $node)) { ++$number; } $generatedUrl = $generatedUrl.'-'.$number; } $node->setUrl($generatedUrl); } public function onUpdate(EntityManagerEvent $event) { $application = new Application($this->kernel); $application->setAutoExit(false); $input = new ArrayInput([ 'command' => 'cache:clear', ]); $output = new BufferedOutput(); $application->run($input, $output); } public function onDelete(EntityManagerEvent $event) { if (!$this->support($event->getEntity())) { return; } $menu = $event->getEntity()->getMenu(); $rootNode = $menu->getRootNode(); if (0 !== count($rootNode->getChildren())) { return; } $childNode = $this->nodeFactory->create($menu); $childNode ->setParent($rootNode) ->setLabel('Premier élément') ; $this->entityManager->update($rootNode, false); $this->entityManager->create($childNode, false); $this->nodeRepository->persistAsFirstChild($childNode, $rootNode); } }