<?php
namespace App\EventSubscriber;
use App\Entity\Workflow\WorkflowLoggableInterface;
use App\Entity\Workflow\WorkflowTransitionLog;
use App\Services\TokenService;
use Doctrine\ORM\EntityManagerInterface;
use ERP\CommentBundle\Entity\Comment;
use ERP\CommentBundle\Entity\CommentableInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Workflow\Event\Event;
class WorkflowLoggerSubscriber implements EventSubscriberInterface
{
/**
* @var TokenService
*/
private $tokenService;
private EntityManagerInterface $entityManager;
public function __construct(TokenService $tokenService, EntityManagerInterface $entityManager)
{
$this->tokenService = $tokenService;
$this->entityManager = $entityManager;
}
public function onEntered(Event $event)
{
$entity = $event->getSubject();
if (!$entity instanceof WorkflowLoggableInterface || !$event->getTransition()) {
return;
}
$workflowTransitionLog = new WorkflowTransitionLog();
$workflowTransitionLog->setName($event->getWorkflowName());
$workflowTransitionLog->setFrom(implode(',', $event->getTransition()->getFroms()));
$workflowTransitionLog->setTo(implode(',', $event->getTransition()->getTos()));
if (($user = $this->tokenService->getUser())) {
$workflowTransitionLog->setUser($user);
}
if ($entity instanceof CommentableInterface) {
foreach ($entity->getComments() as $comment) {
if (isset($comment->workflow_comment) && true === $comment->workflow_comment) {
unset($comment->workflow_comment);
if ($comment instanceof Comment) {
$workflowTransitionLog->setComment($comment);
}
}
}
}
$this->entityManager->persist($workflowTransitionLog);
$entity->addWorkflowTransitionLog($workflowTransitionLog);
}
public static function getSubscribedEvents()
{
return [
'workflow.entered' => 'onEntered',
];
}
}