Passed
Pull Request — master (#359)
by Dmitriy
08:14
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
/**
16
 * ContentNegotiator supports response format negotiation.
17
 */
18
final class ContentNegotiator implements MiddlewareInterface
19
{
20
    private array $contentFormatters;
21
22 5
    public function __construct(array $contentFormatters)
23
    {
24 5
        $this->checkFormatters($contentFormatters);
25 4
        $this->contentFormatters = $contentFormatters;
26 4
    }
27
28
    /**
29
     * @param array $contentFormatters
30
     */
31 1
    public function withContentFormatters(array $contentFormatters): self
32
    {
33 1
        $this->checkFormatters($contentFormatters);
34
        $new = clone $this;
35
        $new->contentFormatters = $contentFormatters;
36
        return $new;
37
    }
38
39 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
40
    {
41 3
        $response = $handler->handle($request);
42 3
        if ($response instanceof DataResponse && !$response->hasResponseFormatter()) {
43 3
            $accepted = $request->getHeader('accept');
44
45 3
            foreach ($accepted as $accept) {
46 3
                foreach ($this->contentFormatters as $contentType => $formatter) {
47 3
                    if (strpos($accept, $contentType) !== false) {
48 3
                        return $response->withResponseFormatter($formatter);
49
                    }
50
                }
51
            }
52
        }
53
54
        return $response;
55
    }
56
57 5
    private function checkFormatters(array $contentFormatters): void
58
    {
59 5
        foreach ($contentFormatters as $contentType => $formatter) {
60 5
            if (!(is_string($contentType) && $formatter instanceof DataResponseFormatterInterface)) {
61 2
                throw new \RuntimeException('Invalid formatter type.');
62
            }
63
        }
64 4
    }
65
}
66
67