110 lines
2.8 KiB
PHP
110 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\EventSuscriber\Site;
|
|
|
|
use App\Entity\EntityInterface;
|
|
use App\Entity\Site\Node;
|
|
use App\Event\EntityManager\EntityManagerEvent;
|
|
use App\EventSuscriber\EntityManagerEventSubscriber;
|
|
use App\Factory\Site\NodeFactory;
|
|
use App\Manager\EntityManager;
|
|
use App\Repository\Site\NodeRepository;
|
|
use App\Slugify\Slugify;
|
|
use Symfony\Component\HttpKernel\KernelInterface;
|
|
|
|
/**
|
|
* class NodeEventSubscriber.
|
|
*
|
|
* @author Simon Vieille <simon@deblan.fr>
|
|
*/
|
|
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,
|
|
Slugify $slugify
|
|
) {
|
|
$this->nodeFactory = $nodeFactory;
|
|
$this->nodeRepository = $nodeRepository;
|
|
$this->entityManager = $entityManager;
|
|
$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 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);
|
|
}
|
|
}
|