<?php
declare(strict_types=1);
namespace App\Api\EventListener;
use App\Api\Entity\Document;
use App\Api\Entity\DocumentType;
use App\Api\Entity\Exemption;
use App\Api\Enum\ExemptionStatus;
use App\Api\Event\ExemptionUpdateEvent;
use App\Api\Messenger\Message\Email\ExemptionToValidateToEmployee;
use App\Api\Messenger\Message\Email\ExemptionToValidateToScope;
use App\Api\Messenger\MessageHandler\Email\ExemptionToValidateToEmployeeHandler;
use App\Api\Messenger\MessageHandler\Email\ExemptionToValidateToScopeHandler;
use Symfony\Component\Messenger\MessageBusInterface;
class ExemptionStatusChangeListener
{
private $messageBus;
private $exemptionToValidateToEmployeeHandler;
private $exemptionToValidateToScopeHandler;
private $isRabbitMqAvailable;
public function __construct(
MessageBusInterface $messageBus,
ExemptionToValidateToEmployeeHandler $exemptionToValidateToEmployeeHandler,
ExemptionToValidateToScopeHandler $exemptionToValidateToScopeHandler,
bool $isRabbitMqAvailable
) {
$this->messageBus = $messageBus;
$this->exemptionToValidateToEmployeeHandler = $exemptionToValidateToEmployeeHandler;
$this->exemptionToValidateToScopeHandler = $exemptionToValidateToScopeHandler;
$this->isRabbitMqAvailable = $isRabbitMqAvailable;
}
public function handle(ExemptionUpdateEvent $exemptionUpdateEvent)
{
$exemption = $exemptionUpdateEvent->getExemption();
if (ExemptionStatus::TO_FINALISE()->equals($exemption->getStatus())) {
if ($this->isReadyToValidate($exemption)) {
$exemption->setStatus(ExemptionStatus::TO_VALIDATE());
// because platform sometimes has problem with RabbitMQ container
$exemptionToValidateToEmployee = new ExemptionToValidateToEmployee($exemption->getId());
$exemptionToValidateToScope = new ExemptionToValidateToScope($exemption->getId(), $exemption->getEmail());
if ($this->isRabbitMqAvailable) {
$this->messageBus->dispatch($exemptionToValidateToEmployee);
$this->messageBus->dispatch($exemptionToValidateToScope);
} else {
$this->exemptionToValidateToEmployeeHandler->handle($exemptionToValidateToEmployee);
$this->exemptionToValidateToScopeHandler->handle($exemptionToValidateToScope);
}
// because platform sometimes has problem with RabbitMQ container
}
}
if (ExemptionStatus::TO_RENEW()->equals($exemption->getStatus())) {
$exemption->setStatus(ExemptionStatus::TO_FINALISE());
}
}
public function isReadyToValidate(Exemption $entity): bool
{
$exemptionReason = $entity->getExemptionReason();
if (!$entity->hasDocument() || !$exemptionReason) {
return false;
}
$existingTypes = [];
/** @var Document $document */
foreach ($exemptionReason->getDocuments() as $document) {
$existingTypes[] = $document->getTypeCode()->getValue();
}
$supportedDocumentTypes = $exemptionReason->getReason()->getDocumentTypes();
/** @var DocumentType $type */
foreach ($supportedDocumentTypes as $type) {
if (!in_array($type->getCode()->getValue(), $existingTypes)) {
return false;
}
}
return true;
}
}