src/Kernel.php line 34

Open in your IDE?
  1. <?php
  2. namespace App;
  3. use App\Helper\Api\JsonFormatter\Throwable\Formatter;
  4. use Exception;
  5. use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\HttpKernelInterface;
  9. use Symfony\Component\HttpKernel\Kernel as BaseKernel;
  10. /**
  11.  * Extends kernel to allow capturing of some exceptions for API routes on not fully initialized kernel.
  12.  *
  13.  * @package API
  14.  * @internal
  15.  */
  16. class Kernel extends BaseKernel
  17. {
  18.     use MicroKernelTrait;
  19.     /**
  20.      * Override {@link BaseKernel::handle()} to capture some exceptions for API routes on not fully initialized kernel.
  21.      *
  22.      * @param Request $request
  23.      * @param int $type
  24.      * @param bool $catch
  25.      * @return Response
  26.      * @throws Exception
  27.      * @noinspection PhpUnused
  28.      */
  29.     public function handle(
  30.         Request $request,
  31.         int $type HttpKernelInterface::MAIN_REQUEST,
  32.         bool $catch true
  33.     ): Response {
  34.         try {
  35.             // call parent method to allow regular process flow
  36.             return parent::handle($request$type$catch);
  37.         } catch (Exception $exception) {
  38.             // handle some unexpected errors before kernel was fully initialized
  39.             if (preg_match('/^\/api\//'$request->getRequestUri())) {
  40.                 // only return JSON for API routes
  41.                 return Formatter::staticFormat($exception);
  42.             }
  43.             // bubble exception for other routes to allow regular process flow
  44.             throw $exception;
  45.         }
  46.     }
  47. }