Passed
Pull Request — master (#233)
by Dmitriy
02:03
created

JsonResponseFormatter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 31
rs 10
c 2
b 0
f 0
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 8 1
A withOptions() 0 5 1
A withContentType() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web\Formatter;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Yiisoft\Serializer\JsonSerializer;
9
use Yiisoft\Yii\Web\WebResponse;
10
11
final class JsonResponseFormatter implements ResponseFormatterInterface
12
{
13
    /**
14
     * @var string the Content-Type header for the response
15
     */
16
    private string $contentType = 'application/json';
17
18
    private int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
19
20
    public function format(WebResponse $webResponse): ResponseInterface
21
    {
22
        $jsonSerializer = new JsonSerializer($this->options);
23
        $content = $jsonSerializer->serialize($webResponse->getData());
24
        $response = $webResponse->getResponse();
25
        $response->getBody()->write($content);
26
27
        return $response->withHeader('Content-Type', $this->contentType);
28
    }
29
30
    public function withOptions(int $options): self
31
    {
32
        $formatter = clone $this;
33
        $formatter->options = $options;
34
        return $formatter;
35
    }
36
37
    public function withContentType(string $contentType): self
38
    {
39
        $formatter = clone $this;
40
        $formatter->contentType = $contentType;
41
        return $formatter;
42
    }
43
}
44