Passed
Pull Request — master (#233)
by Dmitriy
02:20
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 __construct() 0 3 1
A format() 0 7 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 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