Passed
Push — master ( b02cff...0547e2 )
by Alexander
02:42
created

JsonDataResponseFormatter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

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

3 Methods

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