<?php
declare(strict_types=1);
namespace ERP\AccountingBundle\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use ERP\AccountingBundle\Entity\Invoice;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\Transition;
class WorkflowTransitionNotifier implements EventSubscriberInterface
{
/**
* @var Registry
*/
private $workflowRegistry;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(
Registry $workflowRegistry,
EntityManagerInterface $entityManager
) {
$this->workflowRegistry = $workflowRegistry;
$this->entityManager = $entityManager;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['onCreateEnterDraft', EventPriorities::POST_WRITE],
],
'workflow.invoice.entered' => 'onEntered',
];
}
public function onCreateEnterDraft(ViewEvent $event): void
{
if ('POST' === $event->getRequest()->getMethod() && (($invoice = $event->getControllerResult()) instanceof Invoice)) {
if (Invoice::STATUS_EXPECTED === $invoice->getStatus()) {
$applyTransition = 'create_expected';
} else {
$applyTransition = 'create_unpaid';
}
$workflow = $this->workflowRegistry->get($invoice);
$enabledTransitions = new ArrayCollection($workflow->getEnabledTransitions($invoice));
if ($enabledTransitions->exists(function ($key, Transition $transition) use ($applyTransition) {
return $applyTransition === $transition->getName();
})) {
$transition = $enabledTransitions
->filter(function (Transition $transition) use ($applyTransition) {
return $applyTransition === $transition->getName();
})
->first();
$workflow->apply($invoice, $transition->getName());
$this->entityManager->flush();
}
}
}
}