Passed
Pull Request — master (#73)
by Dmitriy
19:02 queued 04:11
created

JsonResponseFormatter::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\StreamFactoryInterface;
9
use Yiisoft\Serializer\JsonSerializer;
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
    private StreamFactoryInterface $streamFactory;
21
22
    public function __construct(
23
        JsonSerializer $jsonSerializer,
24
        StreamFactoryInterface $streamFactory
25
    ) {
26
        $this->jsonSerializer = $jsonSerializer;
27
        $this->streamFactory = $streamFactory;
28
    }
29
30
    public function format(Response $deferredResponse): ResponseInterface
31
    {
32
        $content = $this->jsonSerializer->serialize($deferredResponse->getData());
33
        $response = $deferredResponse->getResponse();
34
        $response->getBody()->write($content);
35
36
        return $response->withHeader('Content-Type', $this->contentType);
37
    }
38
}
39