<?php
namespace App\EventListener\PostValidate;
use App\DTO\Contact\ContactOutput;
use App\DTO\Contact\UpdateContactStatus;
use App\Entity\Contact;
use App\Entity\SiteStatus;
use App\Repository\SiteStatusRepository;
use App\Service\AfterReadStorage;
use App\Service\Manager\ContactManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class UpdateContactStatusPostValidateTransformer implements EventSubscriberInterface
{
/**
* @var SiteStatusRepository
*/
private $siteStatusRepository;
/**
* @var AfterReadStorage
*/
private $afterReadStorage;
/**
* @var ContactManager
*/
private $contactManager;
/**
* @var NormalizerInterface
*/
private $normalizer;
public function __construct(
SiteStatusRepository $siteStatusRepository,
AfterReadStorage $afterReadStorage,
ContactManager $contactManager,
NormalizerInterface $normalizer
) {
$this->siteStatusRepository = $siteStatusRepository;
$this->afterReadStorage = $afterReadStorage;
$this->contactManager = $contactManager;
$this->normalizer = $normalizer;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
PostValidateListener::POST_VALIDATE_TRANSFORMATION => 'transform',
];
}
/**
* @param UpdateContactStatus $payload
*
* @return bool
*/
public function supportTransformation($payload, Request $request)
{
return $payload instanceof UpdateContactStatus && $request->isMethod($request::METHOD_PUT);
}
/**
* @param ViewEvent $event
*/
public function transform(ViewEvent $event)
{
/** @var UpdateContactStatus $payload */
$payload = $event->getControllerResult();
if (!$this->supportTransformation($payload, $event->getRequest())) {
return;
}
/** @var SiteStatus $siteStatus */
$siteStatus = $this->siteStatusRepository->find($payload->statusId);
/** @var Contact $contact */
$contact = $this->afterReadStorage->getObject();
$contact->setStatus($siteStatus);
$this->contactManager->save($contact);
$event->setResponse(new JsonResponse($this->normalizer->normalize($contact, ContactOutput::class)));
}
}