Passed
Push — feature/unit-tests ( e0ee05...a1a6df )
by Daniel
06:55 queued 34s
created

ResponseFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\Factory\Response;
15
16
use Silverback\ApiComponentBundle\Serializer\SerializeFormatResolver;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\Serializer\SerializerInterface;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class ResponseFactory
25
{
26
    private SerializerInterface $serializer;
27
    private SerializeFormatResolver $formatResolver;
28
29
    public function __construct(SerializerInterface $serializer, SerializeFormatResolver $formatResolver)
30
    {
31
        $this->serializer = $serializer;
32
        $this->formatResolver = $formatResolver;
33
    }
34
35
    public function create(Request $request, $response = null, ?int $status = null): Response
36
    {
37
        $headers = [
38
            'Content-Type' => sprintf('%s; charset=utf-8', $request->getMimeType($format = $this->formatResolver->getFormatFromRequest($request))),
39
            'Vary' => 'Accept',
40
            'X-Content-Type-Options' => 'nosniff',
41
            'X-Frame-Options' => 'deny',
42
        ];
43
        if (!\is_string($response)) {
44
            $response = $this->serializer->serialize($response, $format, []);
45
        }
46
47
        return new Response(
48
            $response,
49
            $status ?? Response::HTTP_OK,
50
            $headers
51
        );
52
    }
53
}
54