ERP/AccountingBundle/EventSubscriber/WorkflowTransitionNotifier.php line 17

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace ERP\AccountingBundle\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use Doctrine\Common\Collections\ArrayCollection;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use ERP\AccountingBundle\Entity\Invoice;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Workflow\Registry;
  12. use Symfony\Component\Workflow\Transition;
  13. class WorkflowTransitionNotifier implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var Registry
  17.      */
  18.     private $workflowRegistry;
  19.     /**
  20.      * @var EntityManagerInterface
  21.      */
  22.     private $entityManager;
  23.     public function __construct(
  24.         Registry $workflowRegistry,
  25.         EntityManagerInterface $entityManager
  26.     ) {
  27.         $this->workflowRegistry $workflowRegistry;
  28.         $this->entityManager $entityManager;
  29.     }
  30.     /**
  31.      * {@inheritdoc}
  32.      */
  33.     public static function getSubscribedEvents(): array
  34.     {
  35.         return [
  36.             KernelEvents::VIEW => [
  37.                 ['onCreateEnterDraft'EventPriorities::POST_WRITE],
  38.             ],
  39.             'workflow.invoice.entered' => 'onEntered',
  40.         ];
  41.     }
  42.     public function onCreateEnterDraft(ViewEvent $event): void
  43.     {
  44.         if ('POST' === $event->getRequest()->getMethod() && (($invoice $event->getControllerResult()) instanceof Invoice)) {
  45.             if (Invoice::STATUS_EXPECTED === $invoice->getStatus()) {
  46.                 $applyTransition 'create_expected';
  47.             } else {
  48.                 $applyTransition 'create_unpaid';
  49.             }
  50.             $workflow $this->workflowRegistry->get($invoice);
  51.             $enabledTransitions = new ArrayCollection($workflow->getEnabledTransitions($invoice));
  52.             if ($enabledTransitions->exists(function ($keyTransition $transition) use ($applyTransition) {
  53.                 return $applyTransition === $transition->getName();
  54.             })) {
  55.                 $transition $enabledTransitions
  56.                     ->filter(function (Transition $transition) use ($applyTransition) {
  57.                         return $applyTransition === $transition->getName();
  58.                     })
  59.                     ->first();
  60.                 $workflow->apply($invoice$transition->getName());
  61.                 $this->entityManager->flush();
  62.             }
  63.         }
  64.     }
  65. }