104 lines
3.5 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Workflow\EventSubscriber;
use Chill\MainBundle\Entity\Notification;
use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Chill\MainBundle\Workflow\Helper\MetadataExtractor;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Workflow\Event\Event;
use Symfony\Component\Workflow\Registry;
use function in_array;
class NotificationOnTransition implements EventSubscriberInterface
{
private EngineInterface $engine;
private EntityManagerInterface $entityManager;
private MetadataExtractor $metadataExtractor;
private Registry $registry;
private Security $security;
public function __construct(EntityManagerInterface $entityManager, EngineInterface $engine, MetadataExtractor $metadataExtractor, Security $security, Registry $registry)
{
$this->entityManager = $entityManager;
$this->engine = $engine;
$this->metadataExtractor = $metadataExtractor;
$this->registry = $registry;
$this->security = $security;
}
public static function getSubscribedEvents(): array
{
return [
'workflow.completed' => 'onCompleted',
];
}
public function onCompleted(Event $event): void
{
if (!$event->getSubject() instanceof EntityWorkflow) {
return;
}
/** @var EntityWorkflow $entityWorkflow */
$entityWorkflow = $event->getSubject();
$dests = array_merge(
$entityWorkflow->getSubscriberToStep()->toArray(),
$entityWorkflow->isFinal() ? $entityWorkflow->getSubscriberToFinal()->toArray() : [],
$entityWorkflow->getCurrentStep()->getDestUser()->toArray()
);
$place = $this->metadataExtractor->buildArrayPresentationForPlace($entityWorkflow);
$workflow = $this->metadataExtractor->buildArrayPresentationForWorkflow(
$this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName())
);
$visited = [];
foreach ($dests as $subscriber) {
if (
$this->security->getUser() === $subscriber
|| in_array($subscriber->getId(), $visited, true)
) {
continue;
}
$context = [
'entity_workflow' => $entityWorkflow,
'dest' => $subscriber,
'place' => $place,
'workflow' => $workflow,
'is_dest' => $entityWorkflow->getCurrentStep()->getDestUser()->contains($subscriber),
];
$notification = new Notification();
$notification
->setRelatedEntityId($entityWorkflow->getId())
->setRelatedEntityClass(EntityWorkflow::class)
->setTitle($this->engine->render('@ChillMain/Workflow/workflow_notification_on_transition_completed_title.fr.txt.twig', $context))
->setMessage($this->engine->render('@ChillMain/Workflow/workflow_notification_on_transition_completed_content.fr.txt.twig', $context))
->addAddressee($subscriber);
$this->entityManager->persist($notification);
$visited[] = $subscriber->getId();
}
}
}