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

JsonResponseFormatter   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
dl 0
loc 21
rs 10
c 1
b 0
f 0
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 7 1
A __construct() 0 3 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 JsonSerializer $jsonSerializer;
19
20
    public function __construct()
21
    {
22
        $this->jsonSerializer = new JsonSerializer();
23
    }
24
25
    public function format(WebResponse $webResponse): ResponseInterface
26
    {
27
        $content = $this->jsonSerializer->serialize($webResponse->getData());
28
        $response = $webResponse->getResponse();
29
        $response->getBody()->write($content);
30
31
        return $response->withHeader('Content-Type', $this->contentType);
32
    }
33
}
34