feat(workflow) : listener garantissant un seul workflow isDefault=true
This commit is contained in:
46
src/EventListener/UniqueDefaultWorkflowListener.php
Normal file
46
src/EventListener/UniqueDefaultWorkflowListener.php
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user