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

JsonResponseFormatter   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 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\Response;
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
    private StreamFactoryInterface $streamFactory;
22
23
    public function __construct(
24
        JsonSerializer $jsonSerializer,
25
        StreamFactoryInterface $streamFactory
26
    ) {
27
        $this->jsonSerializer = $jsonSerializer;
28
        $this->streamFactory = $streamFactory;
29
    }
30
31
    public function format(Response $deferredResponse): ResponseInterface
32
    {
33
        $content = $this->jsonSerializer->serialize($deferredResponse->getData());
34
        $response = $deferredResponse->getResponse();
35
        $response->getBody()->write($content);
36
37
        return $response->withHeader('Content-Type', $this->contentType);
38
    }
39
}
40