<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 25/04/2019
* Time: 11:03 AM
*/
namespace App\EventSubscriber\Resource;
use App\Entity\App\ResourceAndTool;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Services\ResourceService;
class ResourcePostSerializerSubscriber implements EventSubscriberInterface
{
private $resourceService;
public function __construct(
ResourceService $resourceService
) {
$this->resourceService = $resourceService;
}
public function onKernelView(ViewEvent $event)
{
$request = $event->getRequest();
$resourceResult = $event->getControllerResult();
$routes = array(
'api_resources_get_collection',
'api_resources_post_collection',
'api_resources_get_item',
'api_resources_put_item',
'api_vendors_resources_get_subresource',
'api_locations_resources_get_subresource'
);
$routesCollection = array(
'api_resources_get_collection',
'api_vendors_resources_get_subresource',
'api_locations_resources_get_subresource'
);
$route = $request->attributes->get('_route');
if (!in_array($route, $routes))
return;
$withChildren = true;
$withParent = true;
$category = $request->query->get('category');
$location = $request->query->get('location');
if ($category || $location || $route == 'api_locations_resources_get_subresource') {
$withChildren = false;
}
if (!ResourceAndTool::SHOW_CHILDREN) {
$withChildren = false;
$withParent = false;
}
$resourceResult = json_decode($resourceResult, true);
if (in_array($route, $routesCollection)) {
foreach ($resourceResult as &$resource) {
$resource = $this->resourceService->formatNormalize(
$resource,
false,
$withChildren,
$route
);
}
$resourceResult = json_encode($resourceResult);
} else {
$resourceResult = $this->resourceService->formatNormalize(
$resourceResult,
$withParent,
$withChildren,
$route
);
$resourceResult = json_encode($resourceResult);
}
$event->setControllerResult($resourceResult);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
}