bundles/CoreBundle/Controller/ErrorController.php line 20

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Bdm\CoreBundle\Controller;
  4. use Bdm\CoreBundle\Exception\PaymentGateway\PaymentGatewayRejectionInterface;
  5. use Doctrine\DBAL\DBALException;
  6. use FOS\RestBundle\View\View;
  7. use FOS\RestBundle\View\ViewHandlerInterface;
  8. use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterface;
  9. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpKernel\Attribute\AsController;
  13. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  14. use Throwable;
  15. #[AsController]
  16. class ErrorController
  17. {
  18. const PDO_ERROR = 'The request cannot be processed. Please contact Payment.net team for additional information.';
  19. public function __construct(
  20. private readonly ViewHandlerInterface $viewHandler,
  21. private readonly ErrorRendererInterface $errorRenderer,
  22. ) {
  23. }
  24. /**
  25. * @SuppressWarnings(PHPMD.Superglobals)
  26. */
  27. private function isPDOException($oException): bool
  28. {
  29. // do not display PDO error only on PROD environment
  30. if (isset($_SERVER['APPLICATION_ENV']) && 'dev' === $_SERVER['APPLICATION_ENV']) {
  31. return false;
  32. }
  33. if ($oException instanceof \PDOException || $oException instanceof \Doctrine\DBAL\Exception) {
  34. return true;
  35. }
  36. if ($oException->getPrevious() instanceof FlattenException) {
  37. return $this->isPDOException($oException->getPrevious());
  38. }
  39. return false;
  40. }
  41. public function __invoke(Throwable $exception, Request $request)
  42. {
  43. if (!$this->viewHandler->supports($request->getRequestFormat())) {
  44. $exception = $this->errorRenderer->render($exception);
  45. return new Response($exception->getAsString(), $exception->getStatusCode(), $exception->getHeaders());
  46. }
  47. $statusCode = 500;
  48. if ($exception instanceof HttpExceptionInterface) {
  49. $statusCode = $exception->getStatusCode();
  50. }
  51. if (!in_array($exception->getMessage(), ['', '0'], true)) {
  52. if ($this->isPDOException($exception)) {
  53. $oMessages['sGlobal'] = self::PDO_ERROR;
  54. } else {
  55. $oMessages['sGlobal'] = $exception->getMessage();
  56. }
  57. } else {
  58. $oMessages['sGlobal'] = 'Internal Server Error';
  59. }
  60. if ($exception instanceof PaymentGatewayRejectionInterface) {
  61. $sStatus = 'rejection';
  62. } else {
  63. $sStatus = 'error';
  64. }
  65. $aResp = [
  66. 'sStatus' => $sStatus,
  67. 'error' => $oMessages['sGlobal'],
  68. 'iErrorCode' => $statusCode,
  69. 'oMessages' => ['sGlobal' => $exception->getMessage()],
  70. ];
  71. $view = View::create(
  72. $aResp,
  73. $statusCode
  74. );
  75. return $this->viewHandler->handle($view, $request);
  76. }
  77. }