<?php
namespace App\EventListener;
use App\Entity\Gos\CancellationFoResponse;
use App\Entity\Gos\OrderPart;
use App\Event\CancellationInFoEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CancellationInFoListener implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public static function getSubscribedEvents(): array
{
return [
CancellationInFoEvent::CANCELLATION_SENT => 'onCancellationSent'
];
}
public function onCancellationSent(CancellationInFoEvent $event): void
{
$orderPart = $event->getOrderPart();
$response = $event->getResponse();
$decodedResponse = json_decode($response, true);
if (!$orderPart->getCancellationFoResponses()->isEmpty())
{
/** @var CancellationFoResponse $cancellationResponse */
$cancellationFoResponse = $orderPart->getCancellationFoResponses()->first();
}
$cancellationFoResponse = $cancellationFoResponse ?? new CancellationFoResponse();
$cancellationFoResponse->setOrderPart($orderPart);
$cancellationFoResponse->setUser($orderPart->getOrders()->getUser());
$cancellationFoResponse->setBody($response);
$cancellationFoResponse->setIsSuccessfully(true);
if (empty($decodedResponse) || array_key_exists('error', $decodedResponse))
{
$this->handleCancellationFailure($event, $orderPart, $response, $cancellationFoResponse);
}
else
{
$cancellationFoResponse->setFailureNumber(null);
}
$this->em->persist($cancellationFoResponse);
$this->em->flush();
}
private function handleCancellationFailure(
CancellationInFoEvent $event,
OrderPart $orderPart,
string $response,
CancellationFoResponse $cancellationFoResponse
): void
{
$failureNumber = $cancellationFoResponse->getFailureNumber();
if (++$failureNumber >= 5)
{
$event->setEmailMessage($orderPart->getOrdTran() . ' - ' . $failureNumber . ' nieudana rezygnacja w FO');
}
$cancellationFoResponse->setFailureNumber($failureNumber);
$cancellationFoResponse->setIsSuccessfully(false);
}
}