Passed
Pull Request — master (#295)
by
unknown
10:47
created

ErrorCatcher::validateRenderer()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 4
nc 3
nop 1
dl 0
loc 8
ccs 0
cts 0
cp 0
crap 12
rs 10
c 1
b 0
f 1
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
        $this->validateRenderer($rendererClass);
50 4
51
        $new = clone $this;
52
        $new->renderers[$this->normalizeMimeType($mimeType)] = $rendererClass;
53
        return $new;
54 4
    }
55 1
56
    public function withOnlyRenderer(string $mimeType, string $rendererClass): self
57
    {
58 3
        $this->validateMimeType($mimeType);
59 3
        $this->validateRenderer($rendererClass);
60 3
61
        $new = clone $this;
62
        $new->renderers = [];
63
        $new->renderers[$this->normalizeMimeType($mimeType)] = $rendererClass;
64
        return $new;
65
    }
66 2
67
    /**
68 2
     * @param string[] $mimeTypes MIME types or, if not specified, all will be removed.
69 2
     */
70 1
    public function withoutRenderers(string ...$mimeTypes): self
71 1
    {
72
        $new = clone $this;
73 1
        if (count($mimeTypes) === 0) {
74 1
            $new->renderers = [];
75 1
            return $new;
76
        }
77 1
        foreach ($mimeTypes as $mimeType) {
78
            $this->validateMimeType($mimeType);
79
            unset($new->renderers[$this->normalizeMimeType($mimeType)]);
80 5
        }
81
        return $new;
82 5
    }
83 5
84 5
    private function handleException(\Throwable $e, ServerRequestInterface $request): ResponseInterface
85 3
    {
86
        $contentType = $this->getContentType($request);
87 5
        $renderer = $this->getRenderer(strtolower($contentType));
88 5
        if ($renderer !== null) {
89 5
            $renderer->setRequest($request);
90 5
        }
91 5
        $content = $this->errorHandler->handleCaughtThrowable($e, $renderer);
92
        $response = $this->responseFactory->createResponse(Status::INTERNAL_SERVER_ERROR)
93
            ->withHeader(Header::CONTENT_TYPE, $contentType);
94 5
        $response->getBody()->write($content);
95
        return $response;
96 5
    }
97 3
98
    private function getRenderer(string $contentType): ?ThrowableRendererInterface
99 2
    {
100
        if (isset($this->renderers[$contentType])) {
101
            return $this->container->get($this->renderers[$contentType]);
102 5
        }
103
        return null;
104
    }
105 5
106 5
    private function getContentType(ServerRequestInterface $request): string
107 2
    {
108
        try {
109
            foreach (HeaderHelper::getSortedAcceptTypes($request->getHeader('accept')) as $header) {
110
                if (array_key_exists($header, $this->renderers)) {
111
                    return $header;
112
                }
113 3
            }
114
        } catch (\InvalidArgumentException $e) {
115
            // The Accept header contains an invalid q factor
116 5
        }
117
        return '*/*';
118
    }
119 5
120 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
121 5
    {
122
        try {
123
            return $handler->handle($request);
124
        } catch (\Throwable $e) {
125
            return $this->handleException($e, $request);
126
        }
127
    }
128 6
129
    /**
130 6
     * @throws \InvalidArgumentException
131 1
     */
132
    private function validateMimeType(string $mimeType): void
133 5
    {
134
        if (strpos($mimeType, '/') === false) {
135 4
            throw new \InvalidArgumentException('Invalid mime type.');
136
        }
137 4
    }
138
139
    private function normalizeMimeType(string $mimeType): string
140 1
    {
141
        return strtolower(trim($mimeType));
142
    }
143
144
    private function validateRenderer(string $rendererClass): void
145
    {
146
        if (trim($rendererClass) === '') {
147
            throw new \InvalidArgumentException('The renderer class cannot be an empty string.');
148
        }
149
150
        if ($this->container->has($rendererClass) === false) {
151
            throw new \InvalidArgumentException("The renderer \"$rendererClass\" cannot be found.");
152
        }
153
    }
154
}
155