<?php
namespace App;
use App\Helper\Api\JsonFormatter\Throwable\Formatter;
use Exception;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
/**
* Extends kernel to allow capturing of some exceptions for API routes on not fully initialized kernel.
*
* @package API
* @internal
*/
class Kernel extends BaseKernel
{
use MicroKernelTrait;
/**
* Override {@link BaseKernel::handle()} to capture some exceptions for API routes on not fully initialized kernel.
*
* @param Request $request
* @param int $type
* @param bool $catch
* @return Response
* @throws Exception
* @noinspection PhpUnused
*/
public function handle(
Request $request,
int $type = HttpKernelInterface::MAIN_REQUEST,
bool $catch = true
): Response {
try {
// call parent method to allow regular process flow
return parent::handle($request, $type, $catch);
} catch (Exception $exception) {
// handle some unexpected errors before kernel was fully initialized
if (preg_match('/^\/api\//', $request->getRequestUri())) {
// only return JSON for API routes
return Formatter::staticFormat($exception);
}
// bubble exception for other routes to allow regular process flow
throw $exception;
}
}
}