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

JsonResponseFormatter   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 22
rs 10
c 2
b 0
f 0
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setOptions() 0 3 1
A format() 0 8 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 setOptions(int $options): void
31
    {
32
        $this->options = $options;
33
    }
34
}
35