Passed
Pull Request — master (#359)
by Dmitriy
05:35 queued 02:56
created

ContentNegotiator::withContentFormatters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.216

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
ccs 2
cts 5
cp 0.4
rs 10
cc 1
nc 1
nop 1
crap 1.216
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web\Middleware;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Yiisoft\DataResponse\DataResponse;
12
use Yiisoft\DataResponse\DataResponseFormatterInterface;
13
14
/**
15
 * ContentNegotiator supports response format negotiation.
16
 */
17
final class ContentNegotiator implements MiddlewareInterface
18
{
19
    private array $contentFormatters;
20
21 5
    public function __construct(array $contentFormatters)
22
    {
23 5
        $this->checkFormatters($contentFormatters);
24 4
        $this->contentFormatters = $contentFormatters;
25 4
    }
26
27
    /**
28
     * @param array $contentFormatters
29
     */
30 1
    public function withContentFormatters(array $contentFormatters): self
31
    {
32 1
        $this->checkFormatters($contentFormatters);
33
        $new = clone $this;
34
        $new->contentFormatters = $contentFormatters;
35
        return $new;
36
    }
37
38 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40 3
        $response = $handler->handle($request);
41 3
        if ($response instanceof DataResponse && !$response->hasResponseFormatter()) {
42 3
            $accepted = $request->getHeader('accept');
43
44 3
            foreach ($accepted as $accept) {
45 3
                foreach ($this->contentFormatters as $contentType => $formatter) {
46 3
                    if (strpos($accept, $contentType) !== false) {
47 3
                        return $response->withResponseFormatter($formatter);
48
                    }
49
                }
50
            }
51
        }
52
53
        return $response;
54
    }
55
56 5
    private function checkFormatters(array $contentFormatters): void
57
    {
58 5
        foreach ($contentFormatters as $contentType => $formatter) {
59 5
            if (!(is_string($contentType) && $formatter instanceof DataResponseFormatterInterface)) {
60 2
                throw new \RuntimeException('Invalid formatter type.');
61
            }
62
        }
63 4
    }
64
}
65