<?php
namespace UVDesk\CommunityPackages\UVDesk\CustomFields\EventListeners;
use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use UVDesk\CommunityPackages\UVDesk\CustomFields\Services\CustomFieldsService;
class RequestEventListener
{
private $firewall;
public function __construct(FirewallMap $firewall, CustomFieldsService $customFields)
{
$this->firewall = $firewall;
$this->customFields = $customFields;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if ('OPTIONS' == $request->getRealMethod()) {
$event->setResponse(new Response());
}
return;
}
public function onKernelResponse(ResponseEvent $event)
{
$request = $event->getRequest();
if (!$event->isMasterRequest()) {
return;
}
$response = $event->getResponse();
if ('OPTIONS' == $request->getRealMethod() || 'POST' == $request->getRealMethod() || 'GET' == $request->getRealMethod()) {
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', ['Access-Control-Allow-Origin', 'Authorization', 'Content-Type']);
}
$supportedRoutes = [
'uvdesk_api_bundle_api_tickets_v1.0_view_ticket',
'uvdesk_api_bundle_api_tickets_v1.0_fetch_tickets',
];
if (in_array($request->get('_route'), $supportedRoutes)) {
$responseContent = json_decode($response->getContent(), true);
switch ($request->get('_route')) {
case 'uvdesk_api_bundle_api_tickets_v1.0_view_ticket':
if (!empty($responseContent['ticket'])) {
$responseContent['ticket']['customFields'] = $this->customFields->getTicketCustomFieldDetails($responseContent['ticket']['id']);
}
break;
case 'uvdesk_api_bundle_api_tickets_v1.0_fetch_tickets':
if (!empty($responseContent['tickets'])) {
$ticketReferenceIds = array_map(function ($ticket) {
return $ticket['id'];
}, $responseContent['tickets']);
$ticketCustomFieldDetailsCollection = $this->customFields->getTicketCustomFieldDetailsCollection($ticketReferenceIds);
foreach ($responseContent['tickets'] as $index => $ticket) {
$responseContent['tickets'][$index]['customFields'] = [];
if (!empty($ticketCustomFieldDetailsCollection[$ticket['id']])) {
$responseContent['tickets'][$index]['customFields'] = $ticketCustomFieldDetailsCollection[$ticket['id']];
}
}
}
break;
default:
break;
}
$response->setContent(json_encode($responseContent));
}
return;
}
}