<?php
namespace App\EventSubscriber;
use App\Utils\ApiResponse;
use App\Exceptions\Api\ApiException;
use App\Controller\Api\BaseApiController;
use App\Utils\Constants\ApiResponseMessages;
use App\Exceptions\Api\ApiValidationException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class ApiSubscriber implements EventSubscriberInterface {
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents(): array {
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::EXCEPTION => 'onKernelException'
];
}
/**
* @param \Symfony\Component\HttpKernel\Event\ControllerEvent $event
*/
public function onKernelController(ControllerEvent $event){
$request = $event->getRequest();
if ($request->getContentType() != 'json' || !$request->getContent()) {
return;
}
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ApiException(ApiResponse::HTTP_BAD_REQUEST, ApiResponseMessages::MSG_INVALID_JSON);
}
$request->request->replace(is_array($data) ? $data : array());
}
/**
* @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event
*/
public function onKernelException(ExceptionEvent $event){
$fromApi = false;
$ex = $event->getThrowable();
$traces = $ex->getTrace();
foreach($traces as $trace){
if (!array_key_exists('class', $trace))
continue;
if (strpos($trace['class'], "App\\Controller\\Api\\") === 0) {
$fromApi = true;
}
}
if ($ex instanceof ApiValidationException) {
$code = method_exists($ex, "getStatusCode") ? $ex->getStatusCode() : 500;
$response = new ApiResponse(
[
"message" => $ex->getMessage(),
"fields" => $ex->getFields()
],
$code
);
$event->setResponse($response);
} elseif ($_ENV['APP_ENV'] !== 'dev' && $ex instanceof NotFoundHttpException) {
$code = method_exists($ex, "getStatusCode") ? $ex->getStatusCode() : 404;
$response = new ApiResponse(
[
"message" => "Requested object is not found."
],
$code
);
$event->setResponse($response);
} elseif ($_ENV['APP_ENV'] !== 'dev' && ($fromApi || $ex instanceof ApiException)) {
if (($ex instanceof FileException)
&& strpos($ex->file, 'FileService.php') !== false
&& is_array($ex->trace)
&& strpos($ex->trace[1]['file'], 'src/Entity/News.php') !== false
&& $ex->trace[1]['function'] === 'upload') {
// skip exception response; handle exception from controller to return custom response
} else {
$code = method_exists($ex, "getStatusCode") ? $ex->getStatusCode() : 500;
$errType = method_exists($ex, "getErrType") ? $ex->getErrType() : '';
$response = new ApiResponse(
[
"message" => $ex->getMessage(),
"code" => $code,
"type" => $errType
],
$code
);
$event->setResponse($response);
}
}
}
}