1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Components 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\ApiComponentsBundle\Factory\Response; |
15
|
|
|
|
16
|
|
|
use Silverback\ApiComponentsBundle\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
|
|
|
|