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

JsonResponseFormatter::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 8
rs 10
c 2
b 0
f 0
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 setOptions(int $options): void
31
    {
32
        $this->options = $options;
33
    }
34
}
35