feat(workflow) : listener garantissant un seul workflow isDefault=true

This commit is contained in:
2026-05-19 19:52:47 +02:00
parent 25f2fc4b16
commit a9f87be8e5

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\Workflow;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
#[AsDoctrineListener(event: Events::onFlush)]
final class UniqueDefaultWorkflowListener
{
public function onFlush(OnFlushEventArgs $args): void
{
$em = $args->getObjectManager();
$uow = $em->getUnitOfWork();
$candidates = [];
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof Workflow && $entity->isDefault()) {
$candidates[] = $entity;
}
}
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if ($entity instanceof Workflow && $entity->isDefault()) {
$candidates[] = $entity;
}
}
if (0 === count($candidates)) {
return;
}
$metadata = $em->getClassMetadata(Workflow::class);
$repo = $em->getRepository(Workflow::class);
foreach ($repo->findBy(['isDefault' => true]) as $existing) {
if (in_array($existing, $candidates, true)) {
continue;
}
$existing->setIsDefault(false);
$uow->recomputeSingleEntityChangeSet($metadata, $existing);
}
}
}