<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\Page;
use App\Event\PageEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
#[AsEventListener(event: PageEvent::PAGE_DELETE_PRE_PERSIST, method: 'softDeleteChildren')]
class SoftDeletePageChildrenSubscriber
{
public function __construct(
private readonly EventDispatcherInterface $eventDispatcher,
private readonly EntityManagerInterface $entityManager,
) {
}
public function softDeleteChildren(PageEvent $event): void
{
$page = $event->getPage();
$deletedAt = $page?->getDeletedAt() ?? new \DateTime('now');
$alreadyHandledPageIds = $event->getPageIdsToPreventRecursion();
if (!\is_int($page?->getId())
|| $alreadyHandledPageIds->has($page->getId())
) {
return;
}
$alreadyHandledPageIds->add($page->getId());
foreach ($page->getSymlinks() as $symlink) {
if (!$symlink->getDeletedAt() instanceof \DateTimeInterface
&& Page::PAGETYPE_SYMLINK === $symlink->getType()
) {
$symlink->setDeletedAt($deletedAt);
$this->entityManager->persist($symlink);
$this->eventDispatcher->dispatch(
new PageEvent(page: $symlink, pageIdsToPreventRecursion: $alreadyHandledPageIds),
PageEvent::PAGE_DELETE_PRE_PERSIST
);
}
}
foreach ($page->getChildren() as $child) {
if (!$child->getDeletedAt() instanceof \DateTimeInterface) {
$child->setDeletedAt($deletedAt);
$this->entityManager->persist($child);
$this->eventDispatcher->dispatch(
new PageEvent(page: $child, pageIdsToPreventRecursion: $alreadyHandledPageIds),
PageEvent::PAGE_DELETE_PRE_PERSIST
);
}
}
}
}