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

JsonResponseFormatter   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

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

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 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