Passed
Pull Request — master (#233)
by Dmitriy
02:20
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
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
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 Psr\Http\Message\StreamFactoryInterface;
9
use Yiisoft\Serializer\JsonSerializer;
10
use Yiisoft\Yii\Web\WebResponse;
11
12
final class JsonResponseFormatter implements ResponseFormatterInterface
13
{
14
    /**
15
     * @var string the Content-Type header for the response
16
     */
17
    private string $contentType = 'application/json';
18
19
    private JsonSerializer $jsonSerializer;
20
21
    public function __construct(JsonSerializer $jsonSerializer)
22
    {
23
        $this->jsonSerializer = $jsonSerializer;
24
    }
25
26
    public function format(WebResponse $webResponse): ResponseInterface
27
    {
28
        $content = $this->jsonSerializer->serialize($webResponse->getData());
29
        $response = $webResponse->getResponse();
30
        $response->getBody()->write($content);
31
32
        return $response->withHeader('Content-Type', $this->contentType);
33
    }
34
}
35