Passed
Pull Request — master (#281)
by
unknown
11:51
created

ErrorCatcher::withAddedRenderer()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.432

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 2
dl 0
loc 14
ccs 7
cts 10
cp 0.7
crap 4.432
rs 9.9666
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 5
    public function __construct(
37
        ResponseFactoryInterface $responseFactory,
38 5
        ErrorHandler $errorHandler,
39 5
        ContainerInterface $container
40 5
    ) {
41 5
        $this->responseFactory = $responseFactory;
42
        $this->errorHandler = $errorHandler;
43 3
        $this->container = $container;
44
    }
45 3
46
    public function withRenderer(string $mimeType, string $rendererClass): self
47
    {
48 3
        $this->validateMimeType($mimeType);
49
50
        if (trim($rendererClass) === '') {
51 3
            throw new \InvalidArgumentException('The renderer class cannot be an empty string.');
52
        }
53
54 3
        if ($this->container->has($rendererClass) === false) {
55 3
            throw new \InvalidArgumentException("The renderer \"$rendererClass\" cannot be found.");
56 3
        }
57
58
        $new = clone $this;
59
        $new->renderers[$this->normalizeMimeType($mimeType)] = $rendererClass;
60
        return $new;
61
    }
62 2
63
    /**
64 2
     * @param string[] $mimeTypes MIME types or, if not specified, all will be removed.
65 2
     */
66 1
    public function withoutRenderers(string ...$mimeTypes): self
67 1
    {
68
        $new = clone $this;
69 1
        if (count($mimeTypes) === 0) {
70 1
            $new->renderers = [];
71
            return $new;
72
        }
73 1
        foreach ($mimeTypes as $mimeType) {
74
            $this->validateMimeType($mimeType);
75 1
            unset($new->renderers[$this->normalizeMimeType($mimeType)]);
76
        }
77
        return $new;
78 5
    }
79
80 5
    private function handleException(\Throwable $e, ServerRequestInterface $request): ResponseInterface
81 5
    {
82 5
        $contentType = $this->getContentType($request);
83 3
        $renderer = $this->getRenderer(strtolower($contentType));
84
        if ($renderer !== null) {
85 5
            $renderer->setRequest($request);
86 5
        }
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
        $response->getBody()->write($content);
91
        return $response;
92 5
    }
93
94 5
    private function getRenderer(string $contentType): ?ThrowableRendererInterface
95 3
    {
96
        if (isset($this->renderers[$contentType])) {
97
            return $this->container->get($this->renderers[$contentType]);
98 2
        }
99
        return null;
100
    }
101 5
102
    private function getContentType(ServerRequestInterface $request): string
103
    {
104 5
        try {
105 5
            foreach (HeaderHelper::getSortedAcceptTypesFromRequest($request) as $header) {
106 2
                if (array_key_exists($header, $this->renderers)) {
107
                    return $header;
108
                }
109
            }
110
        } catch (\InvalidArgumentException $e) {
111
            // The Accept header contains an invalid q factor
112 3
        }
113
        return '*/*';
114
    }
115 5
116
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
117
    {
118 5
        try {
119 5
            return $handler->handle($request);
120 5
        } catch (\Throwable $e) {
121
            return $this->handleException($e, $request);
122
        }
123
    }
124 1
125
    /**
126
     * @throws \InvalidArgumentException
127
     */
128
    private function validateMimeType(string $mimeType): void
129
    {
130
        if (strpos($mimeType, '/') === false) {
131
            throw new \InvalidArgumentException('Invalid mime type.');
132
        }
133
    }
134
135
    private function normalizeMimeType(string $mimeType): string
136
    {
137
        return strtolower(trim($mimeType));
138
    }
139
}
140