<?php
namespace App\EventListener\PostValidate;
use App\DTO\AccountBilling\AccountBilling as AccountBillingDto;
use App\Repository\AccountRepository;
use App\Service\Manager\AccountBillingManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AccountBillingPostValidateTransformer implements EventSubscriberInterface
{
private $accountRepository;
private $accountBillingManager;
private $normalizer;
public function __construct(
AccountRepository $accountRepository,
AccountBillingManager $accountBillingManager,
NormalizerInterface $normalizer
) {
$this->accountRepository = $accountRepository;
$this->accountBillingManager = $accountBillingManager;
$this->normalizer = $normalizer;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
PostValidateListener::POST_VALIDATE_TRANSFORMATION => 'transform',
];
}
/**
* @param AccountBillingDto $payload
*
* @return bool
*/
public function supportTransformation($payload)
{
return $payload instanceof AccountBillingDto;
}
/**
* @param ViewEvent $event
*/
public function transform(ViewEvent $event)
{
/** @var AccountBillingDto $accountBillingDto */
$accountBillingDto = $event->getControllerResult();
if (!$this->supportTransformation($accountBillingDto)) {
return;
}
$account = $this->accountRepository->find($event->getRequest()->get('id'));
if (null === $account) {
throw new NotFoundHttpException();
}
if (null === $accountBilling = $account->getAccountBilling()) {
$accountBilling = $this->accountBillingManager->create(
$account,
$accountBillingDto->companyName,
$accountBillingDto->address,
$accountBillingDto->postCode,
$accountBillingDto->city,
$accountBillingDto->taxNumber,
$accountBillingDto->regulationsAcceptance
);
} else {
$accountBilling->setCompanyName($accountBillingDto->companyName);
$accountBilling->setAddress($accountBillingDto->address);
$accountBilling->setPostCode($accountBillingDto->postCode);
$accountBilling->setCity($accountBillingDto->city);
$accountBilling->setTaxNumber($accountBillingDto->taxNumber);
$accountBilling->setRegulationsAcceptance($accountBillingDto->regulationsAcceptance);
$this->accountBillingManager->save($accountBilling);
}
$event->setResponse(new JsonResponse($this->normalizer->normalize($accountBilling)));
}
}