<?php
/**
* Created by PhpStorm.
* User: sebastiantovar
* Date: 2019-04-04
* Time: 15:24
*/
namespace App\EventSubscriber\Vendor;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Exception\VendorException;
use App\Services\VendorService;
class VendorPostSerializeSubscriber implements EventSubscriberInterface
{
private $vendorService;
public function __construct(VendorService $vendorService)
{
$this->vendorService = $vendorService;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
/**
* @param ViewEvent $event
* @throws VendorException
*/
public function onKernelView(ViewEvent $event) {
$request = $event->getRequest();
$vendorResult = $event->getControllerResult();
$route = $request->attributes->get('_route');
$routes = array(
'api_vendors_get_collection',
'api_vendors_post_collection',
'api_vendors_get_item',
'api_vendors_put_item'
);
if (!in_array($route, $routes))
return;
$vendorResult = json_decode($vendorResult, true);
if ('api_vendors_get_collection' === $route) {
foreach ($vendorResult as &$vendor) {
$vendor = $this->vendorService->formatNormalize($vendor);
}
$vendorResult = json_encode($vendorResult);
} else {
$vendorResult = $this->vendorService->formatNormalize($vendorResult);
$vendorResult = json_encode($vendorResult);
}
$event->setControllerResult($vendorResult);
}
}