<?php
namespace App\EventSubscriber;
use App\Entity\User;
use App\Service\DocumentBackfillService;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
class EasyAdminSubscriber implements EventSubscriberInterface
{
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
private $manager;
/**
* @var DocumentBackfillService
*/
private $backfill;
public function __construct(EntityManagerInterface $manager, DocumentBackfillService $backfill)
{
$this->manager = $manager;
$this->backfill = $backfill;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['checkUser'],
BeforeCrudActionEvent::class => ['backfillScansOnEdit'],
];
}
/**
* When an entity's EDIT page is opened in the admin, retroactively scan
* any of its attached documents that don't yet have an optimized version.
* Generic across every parent type the backfill registry knows about.
*/
public function backfillScansOnEdit(BeforeCrudActionEvent $event): void
{
try {
$context = $event->getAdminContext();
if ($context === null || $context->getCrud() === null) {
return;
}
if (Crud::PAGE_EDIT !== $context->getCrud()->getCurrentPage()) {
return;
}
$entityDto = $context->getEntity();
if ($entityDto === null || !$entityDto->isAccessible()) {
return;
}
$instance = $entityDto->getInstance();
if (is_object($instance) && $this->backfill->supports($instance)) {
$this->backfill->backfillForParent($instance);
}
} catch (\Throwable $e) {
// Never break the admin because of a scan; degradation is handled deeper too.
}
}
public function checkUser(BeforeEntityPersistedEvent $event)
{
/*$entity = $event->getEntityInstance();
if (!($entity instanceof User)) {
return;
}
$user = $this->manager->getRepository( User::class )->findBy( [ 'email' => $entity->getEmail() ] );
if ($user) {
//die;
}*/
}
}