<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 15/04/2019
* Time: 10:24 PM
*/
namespace App\EventSubscriber\MaintenanceElement;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Services\MaintenanceElementService;
class MaintenanceElementPostSerializerSubscriber implements EventSubscriberInterface
{
private $elementService;
public function __construct(
MaintenanceElementService $elementService
) {
$this->elementService = $elementService;
}
public function onKernelView(ViewEvent $event)
{
$request = $event->getRequest();
$maintenanceElementResult = $event->getControllerResult();
$routes = array(
'api_maintenance_elements_get_collection',
'api_maintenance_elements_post_collection',
'api_maintenance_elements_get_item',
'api_maintenance_elements_put_item',
'api_maintenance_elements_childrens_get_subresource',
'api_vendors_maintenance_elements_get_subresource',
'api_locations_maintenance_elements_get_subresource'
);
$routesCollection = array(
'api_maintenance_elements_get_collection',
'api_maintenance_elements_childrens_get_subresource',
'api_vendors_maintenance_elements_get_subresource',
'api_locations_maintenance_elements_get_subresource'
);
$route = $request->attributes->get('_route');
if (!in_array($route, $routes))
return;
$withChildren = true;
$family = $request->query->get('family');
$location = $request->query->get('location');
if ($family || $location || $route == 'api_locations_maintenance_elements_get_subresource') {
$withChildren = false;
}
$maintenanceElementResult = json_decode($maintenanceElementResult, true);
if (in_array($route, $routesCollection)) {
foreach ($maintenanceElementResult as &$maintenanceElement) {
$maintenanceElement = $this->elementService->formatNormalize(
$maintenanceElement,
false,
$withChildren,
$route
);
}
$maintenanceElementResult = json_encode($maintenanceElementResult);
} else {
$maintenanceElementResult = $this->elementService->formatNormalize(
$maintenanceElementResult,
true,
true,
$route
);
$maintenanceElementResult = json_encode($maintenanceElementResult);
}
$event->setControllerResult($maintenanceElementResult);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
}