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

JsonDataResponseFormatter::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 10
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