HttpResponseFactory::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace AppBundle\Service;
4
5
use AppBundle\Response\EmptyApiResponse;
6
use AppBundle\Response\FileResponse;
7
use AppBundle\Response\Infrastructure\AbstractApiResponse;
8
use JMS\Serializer\Serializer;
9
use Symfony\Component\HttpFoundation\BinaryFileResponse;
10
use Symfony\Component\HttpFoundation\Response;
11
12
/**
13
 * @author Vehsamrak
14
 */
15
class HttpResponseFactory
16
{
17
    const FORMAT_JSON = 'json';
18
19
    /** @var Serializer */
20
    private $serializer;
21
22 44
    public function __construct(Serializer $serializer) {
23 44
        $this->serializer = $serializer;
24 44
    }
25
26 44
    public function createResponse(AbstractApiResponse $apiResponse): Response
27
    {
28 44
        $serializedData = $this->serialize($apiResponse);
29
30 44
        if ($apiResponse instanceof FileResponse) {
31 1
            $response = new BinaryFileResponse($apiResponse->getFile(), $apiResponse->getHttpCode());
32
        } else {
33 44
            $response = new Response($serializedData, $apiResponse->getHttpCode());
34
        }
35
        
36 44
        return $response;
37
    }
38
39 44
    private function serialize(AbstractApiResponse $apiResponse): string
40
    {
41 44
        if (!$apiResponse instanceof EmptyApiResponse) {
42 42
            $serializedData = $this->serializer->serialize($apiResponse, self::FORMAT_JSON);
43
        }
44
45 44
        return $serializedData ?? '';
46
    }
47
}
48