<?php
declare(strict_types=1);
namespace Bdm\CoreBundle\Controller;
use Bdm\CoreBundle\Exception\PaymentGateway\PaymentGatewayRejectionInterface;
use Doctrine\DBAL\DBALException;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandlerInterface;
use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterface;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Throwable;
#[AsController]
class ErrorController
{
const PDO_ERROR = 'The request cannot be processed. Please contact Payment.net team for additional information.';
public function __construct(
private readonly ViewHandlerInterface $viewHandler,
private readonly ErrorRendererInterface $errorRenderer,
) {
}
/**
* @SuppressWarnings(PHPMD.Superglobals)
*/
private function isPDOException($oException): bool
{
// do not display PDO error only on PROD environment
if (isset($_SERVER['APPLICATION_ENV']) && 'dev' === $_SERVER['APPLICATION_ENV']) {
return false;
}
if ($oException instanceof \PDOException || $oException instanceof \Doctrine\DBAL\Exception) {
return true;
}
if ($oException->getPrevious() instanceof FlattenException) {
return $this->isPDOException($oException->getPrevious());
}
return false;
}
public function __invoke(Throwable $exception, Request $request)
{
if (!$this->viewHandler->supports($request->getRequestFormat())) {
$exception = $this->errorRenderer->render($exception);
return new Response($exception->getAsString(), $exception->getStatusCode(), $exception->getHeaders());
}
$statusCode = 500;
if ($exception instanceof HttpExceptionInterface) {
$statusCode = $exception->getStatusCode();
}
if (!in_array($exception->getMessage(), ['', '0'], true)) {
if ($this->isPDOException($exception)) {
$oMessages['sGlobal'] = self::PDO_ERROR;
} else {
$oMessages['sGlobal'] = $exception->getMessage();
}
} else {
$oMessages['sGlobal'] = 'Internal Server Error';
}
if ($exception instanceof PaymentGatewayRejectionInterface) {
$sStatus = 'rejection';
} else {
$sStatus = 'error';
}
$aResp = [
'sStatus' => $sStatus,
'error' => $oMessages['sGlobal'],
'iErrorCode' => $statusCode,
'oMessages' => ['sGlobal' => $exception->getMessage()],
];
$view = View::create(
$aResp,
$statusCode
);
return $this->viewHandler->handle($view, $request);
}
}