Passed
Pull Request — master (#281)
by
unknown
12:38 queued 23s
created

ErrorCatcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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