Passed
Push — master ( 4336f6...f96735 )
by Alexander
10:14 queued 07:50
created

ErrorCatcher::validateMimeType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web\ErrorHandler;
6
7
use Psr\Container\ContainerInterface;
8
use Psr\Http\Message\ResponseFactoryInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Yiisoft\Http\Header;
14
use Yiisoft\Http\HeaderHelper;
15
use Yiisoft\Http\Status;
16
17
/**
18
 * ErrorCatcher catches all throwables from the next middlewares and renders it
19
 * according to the content type passed by the client.
20
 */
21
final class ErrorCatcher implements MiddlewareInterface
22
{
23
    private array $renderers = [
24
        'application/json' => JsonRenderer::class,
25
        'application/xml' => XmlRenderer::class,
26
        'text/xml' => XmlRenderer::class,
27
        'text/plain' => PlainTextRenderer::class,
28
        'text/html' => HtmlRenderer::class,
29
        '*/*' => HtmlRenderer::class,
30
    ];
31
32
    private ResponseFactoryInterface $responseFactory;
33
    private ErrorHandler $errorHandler;
34
    private ContainerInterface $container;
35
36 7
    public function __construct(
37
        ResponseFactoryInterface $responseFactory,
38
        ErrorHandler $errorHandler,
39
        ContainerInterface $container
40
    ) {
41 7
        $this->responseFactory = $responseFactory;
42 7
        $this->errorHandler = $errorHandler;
43 7
        $this->container = $container;
44 7
    }
45
46 5
    public function withRenderer(string $mimeType, string $rendererClass): self
47
    {
48 5
        $this->validateMimeType($mimeType);
49
50 4
        if (trim($rendererClass) === '') {
51
            throw new \InvalidArgumentException('The renderer class cannot be an empty string.');
52
        }
53
54 4
        if ($this->container->has($rendererClass) === false) {
55 1
            throw new \InvalidArgumentException("The renderer \"$rendererClass\" cannot be found.");
56
        }
57
58 3
        $new = clone $this;
59 3
        $new->renderers[$this->normalizeMimeType($mimeType)] = $rendererClass;
60 3
        return $new;
61
    }
62
63
    /**
64
     * @param string[] $mimeTypes MIME types or, if not specified, all will be removed.
65
     */
66 2
    public function withoutRenderers(string ...$mimeTypes): self
67
    {
68 2
        $new = clone $this;
69 2
        if (count($mimeTypes) === 0) {
70 1
            $new->renderers = [];
71 1
            return $new;
72
        }
73 1
        foreach ($mimeTypes as $mimeType) {
74 1
            $this->validateMimeType($mimeType);
75 1
            unset($new->renderers[$this->normalizeMimeType($mimeType)]);
76
        }
77 1
        return $new;
78
    }
79
80 5
    private function handleException(\Throwable $e, ServerRequestInterface $request): ResponseInterface
81
    {
82 5
        $contentType = $this->getContentType($request);
83 5
        $renderer = $this->getRenderer(strtolower($contentType));
84 5
        if ($renderer !== null) {
85 3
            $renderer->setRequest($request);
86
        }
87 5
        $content = $this->errorHandler->handleCaughtThrowable($e, $renderer);
88 5
        $response = $this->responseFactory->createResponse(Status::INTERNAL_SERVER_ERROR)
89 5
            ->withHeader(Header::CONTENT_TYPE, $contentType);
90 5
        $response->getBody()->write($content);
91 5
        return $response;
92
    }
93
94 5
    private function getRenderer(string $contentType): ?ThrowableRendererInterface
95
    {
96 5
        if (isset($this->renderers[$contentType])) {
97 3
            return $this->container->get($this->renderers[$contentType]);
98
        }
99 2
        return null;
100
    }
101
102 5
    private function getContentType(ServerRequestInterface $request): string
103
    {
104
        try {
105 5
            foreach (HeaderHelper::getSortedAcceptTypesFromRequest($request) as $header) {
106 5
                if (array_key_exists($header, $this->renderers)) {
107 2
                    return $header;
108
                }
109
            }
110
        } catch (\InvalidArgumentException $e) {
111
            // The Accept header contains an invalid q factor
112
        }
113 3
        return '*/*';
114
    }
115
116 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
117
    {
118
        try {
119 5
            return $handler->handle($request);
120 5
        } catch (\Throwable $e) {
121 5
            return $this->handleException($e, $request);
122
        }
123
    }
124
125
    /**
126
     * @throws \InvalidArgumentException
127
     */
128 6
    private function validateMimeType(string $mimeType): void
129
    {
130 6
        if (strpos($mimeType, '/') === false) {
131 1
            throw new \InvalidArgumentException('Invalid mime type.');
132
        }
133 5
    }
134
135 4
    private function normalizeMimeType(string $mimeType): string
136
    {
137 4
        return strtolower(trim($mimeType));
138
    }
139
}
140