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

JsonResponseFormatter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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