|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * It's free open-source software released under the MIT License. |
| 5 | + * |
| 6 | + * @author Anatoly Nekhay <[email protected]> |
| 7 | + * @copyright Copyright (c) 2018, Anatoly Nekhay |
| 8 | + * @license https://github.com/sunrise-php/http-router/blob/master/LICENSE |
| 9 | + * @link https://github.com/sunrise-php/http-router |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace Sunrise\Http\Router\Middleware; |
| 15 | + |
| 16 | +use Psr\Http\Message\ResponseFactoryInterface; |
| 17 | +use Psr\Http\Message\ResponseInterface; |
| 18 | +use Psr\Http\Message\ServerRequestInterface; |
| 19 | +use Psr\Http\Message\StreamFactoryInterface; |
| 20 | +use Psr\Http\Server\MiddlewareInterface; |
| 21 | +use Psr\Http\Server\RequestHandlerInterface; |
| 22 | +use Psr\Log\LoggerInterface; |
| 23 | +use Sunrise\Coder\CodecManagerInterface; |
| 24 | +use Sunrise\Coder\MediaTypeInterface; |
| 25 | +use Sunrise\Http\Router\Dictionary\HeaderName; |
| 26 | +use Sunrise\Http\Router\Exception\HttpException; |
| 27 | +use Sunrise\Http\Router\Exception\HttpExceptionFactory; |
| 28 | +use Sunrise\Http\Router\LanguageInterface; |
| 29 | +use Sunrise\Http\Router\ServerRequest; |
| 30 | +use Sunrise\Http\Router\Validation\ConstraintViolationInterface; |
| 31 | +use Sunrise\Http\Router\View\ErrorView; |
| 32 | +use Sunrise\Http\Router\View\ViolationView; |
| 33 | +use Sunrise\Translator\TranslatorManagerInterface; |
| 34 | +use Throwable; |
| 35 | + |
| 36 | +use function sprintf; |
| 37 | + |
| 38 | +final class ErrorHandlingMiddleware implements MiddlewareInterface |
| 39 | +{ |
| 40 | + public function __construct( |
| 41 | + private readonly ResponseFactoryInterface $responseFactory, |
| 42 | + private readonly StreamFactoryInterface $streamFactory, |
| 43 | + private readonly CodecManagerInterface $codecManager, |
| 44 | + /** @var array<array-key, mixed> */ |
| 45 | + private readonly array $codecContext, |
| 46 | + /** @var list<MediaTypeInterface> */ |
| 47 | + private readonly array $producedMediaTypes, |
| 48 | + private readonly MediaTypeInterface $defaultMediaType, |
| 49 | + private readonly TranslatorManagerInterface $translatorManager, |
| 50 | + /** @var list<LanguageInterface> */ |
| 51 | + private readonly array $producedLanguages, |
| 52 | + private readonly LanguageInterface $defaultLanguage, |
| 53 | + private readonly LoggerInterface $logger, |
| 54 | + private readonly ?int $fatalErrorStatusCode = null, |
| 55 | + private readonly ?string $fatalErrorMessage = null, |
| 56 | + ) { |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * @inheritDoc |
| 61 | + */ |
| 62 | + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
| 63 | + { |
| 64 | + try { |
| 65 | + return $handler->handle($request); |
| 66 | + } catch (HttpException $e) { |
| 67 | + return $this->handleHttpError($e, $request); |
| 68 | + } catch (Throwable $e) { |
| 69 | + return $this->handleFatalError($e, $request); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + private function handleHttpError(HttpException $error, ServerRequestInterface $request): ResponseInterface |
| 74 | + { |
| 75 | + $clientPreferredMediaType = ServerRequest::create($request) |
| 76 | + ->getClientPreferredMediaType(...$this->producedMediaTypes) |
| 77 | + ?? $this->defaultMediaType; |
| 78 | + |
| 79 | + $clientPreferredLanguage = ServerRequest::create($request) |
| 80 | + ->getClientPreferredLanguage(...$this->producedLanguages) |
| 81 | + ?? $this->defaultLanguage; |
| 82 | + |
| 83 | + return $this->createErrorResponse($error, $clientPreferredMediaType, $clientPreferredLanguage); |
| 84 | + } |
| 85 | + |
| 86 | + private function handleFatalError(Throwable $error, ServerRequestInterface $request): ResponseInterface |
| 87 | + { |
| 88 | + $this->logger->error($error->getMessage(), [ |
| 89 | + 'error' => $error, |
| 90 | + 'request' => $request, |
| 91 | + ]); |
| 92 | + |
| 93 | + $httpError = HttpExceptionFactory::internalServerError( |
| 94 | + message: $this->fatalErrorMessage, |
| 95 | + code: $this->fatalErrorStatusCode, |
| 96 | + previous: $error, |
| 97 | + ); |
| 98 | + |
| 99 | + return $this->handleHttpError($httpError, $request); |
| 100 | + } |
| 101 | + |
| 102 | + private function createErrorResponse( |
| 103 | + HttpException $error, |
| 104 | + MediaTypeInterface $mediaType, |
| 105 | + LanguageInterface $language, |
| 106 | + ): ResponseInterface { |
| 107 | + $response = $this->responseFactory->createResponse($error->getCode()); |
| 108 | + foreach ($error->getHeaderFields() as [$fieldName, $fieldValue]) { |
| 109 | + $response = $response->withHeader($fieldName, $fieldValue); |
| 110 | + } |
| 111 | + |
| 112 | + $errorView = $this->createErrorView($error, $language); |
| 113 | + $responseContent = $this->codecManager->encode($mediaType, $errorView, $this->codecContext); |
| 114 | + $responseContentType = sprintf('%s; charset=UTF-8', $mediaType->getIdentifier()); |
| 115 | + |
| 116 | + return $response->withHeader(HeaderName::CONTENT_TYPE, $responseContentType) |
| 117 | + ->withBody($this->streamFactory->createStream($responseContent)); |
| 118 | + } |
| 119 | + |
| 120 | + private function createErrorView( |
| 121 | + HttpException $error, |
| 122 | + LanguageInterface $language, |
| 123 | + ): ErrorView { |
| 124 | + $message = $this->translatorManager->translate( |
| 125 | + domain: $error->getTranslationDomain(), |
| 126 | + locale: $language->getCode(), |
| 127 | + template: $error->getMessageTemplate(), |
| 128 | + placeholders: $error->getMessagePlaceholders(), |
| 129 | + ); |
| 130 | + |
| 131 | + $violationViews = []; |
| 132 | + foreach ($error->getConstraintViolations() as $violation) { |
| 133 | + $violationViews[] = $this->createViolationView($violation, $language); |
| 134 | + } |
| 135 | + |
| 136 | + return new ErrorView( |
| 137 | + message: $message, |
| 138 | + violations: $violationViews, |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + private function createViolationView( |
| 143 | + ConstraintViolationInterface $violation, |
| 144 | + LanguageInterface $language, |
| 145 | + ): ViolationView { |
| 146 | + $message = $this->translatorManager->translate( |
| 147 | + domain: $violation->getTranslationDomain(), |
| 148 | + locale: $language->getCode(), |
| 149 | + template: $violation->getMessageTemplate(), |
| 150 | + placeholders: $violation->getMessagePlaceholders(), |
| 151 | + ); |
| 152 | + |
| 153 | + return new ViolationView( |
| 154 | + source: $violation->getPropertyPath(), |
| 155 | + message: $message, |
| 156 | + code: $violation->getCode(), |
| 157 | + ); |
| 158 | + } |
| 159 | +} |
0 commit comments