<?php
/**
* This file is part of the CosaVostra, TrackPay package.
*
* (c) Mohamed Radhi GUENNICHI <rg@mate.tn> <+216 50 711 816>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\Organization;
use App\Entity\Procedure;
use App\Event\CustomerWorkflowChangedEvent;
use App\Manager\ProcedureManager;
use App\Repository\ProcedureRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerWorkflowChangedSubscriber implements EventSubscriberInterface
{
/**
* @var ProcedureManager
*/
protected $procedureManager;
/**
* @var ProcedureRepository
*/
protected $procedureRepository;
/**
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct(ProcedureManager $procedureManager, ProcedureRepository $procedureRepository, EntityManagerInterface $entityManager)
{
$this->procedureRepository = $procedureRepository;
$this->entityManager = $entityManager;
$this->procedureManager = $procedureManager;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
CustomerWorkflowChangedEvent::class => 'onWorkflowChanged'
];
}
public function onWorkflowChanged(CustomerWorkflowChangedEvent $event): void
{
// Get procedures with pending/paused status
$customer = $event->getCustomer();
$procedures = $this->getNotActivatedProceduresFor($customer);
// Remove the pendingStep and dispatchedStep objects
foreach ($procedures as $procedure) {
$procedure->setWorkflow(
$customer->getWorkflow()
);
$procedure->setDispatchedStep(null);
// Remove the dispatchedStep object, we don't need it anymore here.
if (null !== $procedure->getPendingStep()) {
$this->entityManager->remove($procedure->getPendingStep());
$procedure->setPendingStep(null);
}
// Flush changes.
$this->entityManager->flush();
// Process the new workflow
$this->procedureManager->proceed($procedure);
}
}
/**
* @param Organization $customer
*
* @return Procedure[]
*/
protected function getNotActivatedProceduresFor(Organization $customer): array
{
$queryBuilder = $this->procedureRepository->createQueryBuilder('o');
return $queryBuilder
->innerJoin('o.invoice', 'invoice')
->andWhere(
$queryBuilder->expr()->eq('invoice.customer', ':customer')
)
->andWhere(
$queryBuilder->expr()->in('o.status', ':status')
)
->andWhere(
$queryBuilder->expr()->isNull('o.activatedAt')
)
->setParameters([
'customer' => $customer,
'status' => [Procedure::STATUS_PENDING, Procedure::STATUS_PAUSED]
])
->getQuery()
->getResult();
}
}