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\Action; |
15
|
|
|
|
16
|
|
|
use Silverback\ApiComponentBundle\Exception\InvalidParameterException; |
17
|
|
|
use Silverback\ApiComponentBundle\Serializer\RequestFormatResolver; |
18
|
|
|
use Symfony\Component\HttpFoundation\Request; |
19
|
|
|
use Symfony\Component\HttpFoundation\Response; |
20
|
|
|
use Symfony\Component\Serializer\Encoder\DecoderInterface; |
21
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @author Daniel West <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
class AbstractAction |
27
|
|
|
{ |
28
|
|
|
protected DecoderInterface $serializer; |
29
|
|
|
protected RequestFormatResolver $requestFormatResolver; |
30
|
|
|
|
31
|
|
|
public function __construct(SerializerInterface $serializer, RequestFormatResolver $requestFormatResolver) |
32
|
|
|
{ |
33
|
|
|
if (!$serializer instanceof DecoderInterface) { |
34
|
|
|
throw new InvalidParameterException(sprintf('The serializer injected into %s should implement %s', __CLASS__, DecoderInterface::class)); |
35
|
|
|
} |
36
|
|
|
$this->serializer = $serializer; |
37
|
|
|
$this->requestFormatResolver = $requestFormatResolver; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
protected function getFormat(Request $request): string |
41
|
|
|
{ |
42
|
|
|
return $this->requestFormatResolver->getFormatFromRequest($request); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function getResponse(Request $request, $response = null, ?int $status = null): Response |
46
|
|
|
{ |
47
|
|
|
$headers = [ |
48
|
|
|
'Content-Type' => sprintf('%s; charset=utf-8', $format = $this->getFormat($request)), |
49
|
|
|
'Vary' => 'Accept', |
50
|
|
|
'X-Content-Type-Options' => 'nosniff', |
51
|
|
|
'X-Frame-Options' => 'deny', |
52
|
|
|
]; |
53
|
|
|
if (!\is_string($response)) { |
54
|
|
|
$response = $this->serializer->serialize($response, $format, []); |
|
|
|
|
55
|
|
|
} |
56
|
|
|
new Response( |
57
|
|
|
$response, |
58
|
|
|
$status ?? Response::HTTP_OK, |
59
|
|
|
$headers |
60
|
|
|
); |
|
|
|
|
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|