<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 26/04/2019
* Time: 11:33 AM
*/
namespace App\EventSubscriber\Location;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Services\LocationService;
class LocationPostSerializerSubscriber implements EventSubscriberInterface
{
private $locationService;
public function __construct(LocationService $locationService)
{
$this->locationService = $locationService;
}
/**
* @param ViewEvent $event
*/
public function onKernelView(ViewEvent $event)
{
$request = $event->getRequest();
$locationResult = $event->getControllerResult();
$routes = array(
'api_locations_get_collection',
'api_locations_post_collection',
'api_locations_get_item',
'api_locations_put_item',
'api_vendors_locations_get_subresource'
);
$route = $request->attributes->get('_route');
if (!in_array($route, $routes)) {
return;
}
$locationResult = json_decode($locationResult, true);
if ('api_locations_get_collection' === $route ||
'api_vendors_locations_get_subresource' === $route) {
foreach ($locationResult as &$location) {
$location = $this->locationService->formatNormalize($location, $route);
}
} else {
$locationResult = $this->locationService->formatNormalize($locationResult, $route);
}
$locationResult = json_encode($locationResult);
$event->setControllerResult($locationResult);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
}