Passed
Pull Request — master (#296)
by Alexander
13:38
created

ErrorCatcher::getRenderer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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