tinternet.net/src/EventSuscriber/Site/NodeEventSubscriber.php
2021-03-19 15:13:42 +01:00

128 lines
3.4 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\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
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,
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);
}
}