<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 05/08/2019
* Time: 08:12 PM
*/
namespace App\EventSubscriber\Indicator;
use App\Entity\App\Vendor;
use App\Repository\App\VendorRepository;
use App\Services\UtilsService;
use App\Services\IndicatorService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\HttpKernel\KernelEvents;
class IndicatorPostSerializerSubscriber implements EventSubscriberInterface
{
private $utilsService;
private $vendorRepository;
private $indicatorService;
public function __construct(
UtilsService $utilsService,
VendorRepository $vendorRepository,
IndicatorService $indicatorService
) {
$this->utilsService = $utilsService;
$this->vendorRepository = $vendorRepository;
$this->indicatorService = $indicatorService;
}
/**
* @param ViewEvent $event
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function onKernelView(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$request = $event->getRequest();
$indicatorResult = $event->getControllerResult();
$routes = array(
'api_indicators_get_collection'
);
$route = $request->attributes->get('_route');
if (!in_array($route, $routes)) {
return;
}
$vendor = null;
if ($request->query->has('vendor')) {
$vendor = $this->vendorRepository->find($request->query->get('vendor'));
}
$requestSearch = [];
if ($request->query->has('year')) {
$requestSearch['year'] = $request->query->get('year');
}
if ($vendor instanceof Vendor) {
$indicatorResult = json_decode($indicatorResult, true);
foreach ($indicatorResult as &$indicator) {
$indicator = $this->indicatorService->calculateIndicators($indicator, $vendor, $requestSearch);
}
$indicatorResult = json_encode($indicatorResult);
$event->setControllerResult($indicatorResult);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_SERIALIZE]
];
}
}