<?php
/**
* Created by PhpStorm.
* User: sebastiantovar
* Date: 2019-04-15
* Time: 18:36
*/
namespace App\EventSubscriber\Category;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Services\CategoryService;
use App\Services\UtilsService;
class CategoryPostSerializeSubscriber implements EventSubscriberInterface
{
private $categoryService;
private $utilsService;
public function __construct(
UtilsService $utilsService,
CategoryService $categoryService
) {
$this->utilsService = $utilsService;
$this->categoryService = $categoryService;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
/**
* @param ViewEvent $event
*/
public function onKernelView(ViewEvent $event) {
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$request = $event->getRequest();
$categoryResult = $event->getControllerResult();
$route = $request->attributes->get('_route');
$routes = array(
'api_categories_post_collection',
'api_categories_get_item',
'api_categories_put_item',
'api_vendors_categories_get_subresource'
);
if (!in_array($route, $routes))
return;
$categoryResult = json_decode($categoryResult, true);
if ('api_categories_get_collection' === $route ||
'api_vendors_categories_get_subresource' === $route) {
foreach ($categoryResult as &$category) {
$category = $this->categoryService->formatNormalize($category, false, $route);
}
} else {
$categoryResult = $this->categoryService->formatNormalize($categoryResult,true, $route);
}
$categoryResult = json_encode($categoryResult);
$event->setControllerResult($categoryResult);
}
}