src/EventSubscriber/SoftDeletePageChildrenSubscriber.php line 22

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\Page;
  5. use App\Event\PageEvent;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
  8. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  9. #[AsEventListener(eventPageEvent::PAGE_DELETE_PRE_PERSISTmethod'softDeleteChildren')]
  10. class SoftDeletePageChildrenSubscriber
  11. {
  12.     public function __construct(
  13.         private readonly EventDispatcherInterface $eventDispatcher,
  14.         private readonly EntityManagerInterface $entityManager,
  15.     ) {
  16.     }
  17.     public function softDeleteChildren(PageEvent $event): void
  18.     {
  19.         $page $event->getPage();
  20.         $deletedAt $page?->getDeletedAt() ?? new \DateTime('now');
  21.         $alreadyHandledPageIds $event->getPageIdsToPreventRecursion();
  22.         if (!\is_int($page?->getId())
  23.             || $alreadyHandledPageIds->has($page->getId())
  24.         ) {
  25.             return;
  26.         }
  27.         $alreadyHandledPageIds->add($page->getId());
  28.         foreach ($page->getSymlinks() as $symlink) {
  29.             if (!$symlink->getDeletedAt() instanceof \DateTimeInterface
  30.                 && Page::PAGETYPE_SYMLINK === $symlink->getType()
  31.             ) {
  32.                 $symlink->setDeletedAt($deletedAt);
  33.                 $this->entityManager->persist($symlink);
  34.                 $this->eventDispatcher->dispatch(
  35.                     new PageEvent(page$symlinkpageIdsToPreventRecursion$alreadyHandledPageIds),
  36.                     PageEvent::PAGE_DELETE_PRE_PERSIST
  37.                 );
  38.             }
  39.         }
  40.         foreach ($page->getChildren() as $child) {
  41.             if (!$child->getDeletedAt() instanceof \DateTimeInterface) {
  42.                 $child->setDeletedAt($deletedAt);
  43.                 $this->entityManager->persist($child);
  44.                 $this->eventDispatcher->dispatch(
  45.                     new PageEvent(page$childpageIdsToPreventRecursion$alreadyHandledPageIds),
  46.                     PageEvent::PAGE_DELETE_PRE_PERSIST
  47.                 );
  48.             }
  49.         }
  50.     }
  51. }