Completed
Push — develop ( 99c8cd...370699 )
by Baptiste
02:34
created

ResponseTranslator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Rest\ServerBundle\Translator;
5
6
use Innmind\Http\{
7
    Message\ResponseInterface,
8
    HeadersInterface,
9
    Header\HeaderValueInterface
10
};
11
use Innmind\Immutable\Map;
12
use Symfony\Component\HttpFoundation\Response;
13
14
final class ResponseTranslator
15
{
16
    private $transformed;
17
18
    public function __construct()
19
    {
20
        $this->transformed = new Map(
21
            ResponseInterface::class,
22
            Response::class
23
        );
24
    }
25
26
    public function translate(ResponseInterface $response): Response
27
    {
28
        if ($this->transformed->contains($response)) {
29
            return $this->transformed->get($response);
30
        }
31
32
        $sfResponse = (new Response(
33
            (string) $response->body(),
34
            $response->statusCode()->value(),
35
            $this->translateHeaders($response->headers())
36
        ))
37
            ->setProtocolVersion((string) $response->protocolVersion());
38
        $this->transformed = $this->transformed->put(
39
            $response,
40
            $sfResponse
41
        );
42
43
        return $sfResponse;
44
    }
45
46
    private function translateHeaders(HeadersInterface $headers): array
47
    {
48
        $raw = [];
49
50
        foreach ($headers as $header) {
51
            $raw[$header->name()] = $header
52
                ->values()
53
                ->reduce(
54
                    [],
55
                    function(array $carry, HeaderValueInterface $value) {
56
                        $carry[] = (string) $value;
57
58
                        return $carry;
59
                    }
60
                );
61
        }
62
63
        return $raw;
64
    }
65
}
66