|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Maba\Bundle\RestBundle\Service; |
|
5
|
|
|
|
|
6
|
|
|
use RuntimeException; |
|
7
|
|
|
use Exception; |
|
8
|
|
|
use InvalidArgumentException; |
|
9
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @internal |
|
13
|
|
|
*/ |
|
14
|
|
|
class ResponseBuilder |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Builds HTTP Response object by provided data |
|
18
|
|
|
* |
|
19
|
|
|
* @param mixed $data |
|
20
|
|
|
* @param int $statusCode |
|
21
|
|
|
* @return Response |
|
22
|
|
|
* @throws Exception |
|
23
|
|
|
*/ |
|
24
|
43 |
|
public function buildResponse($data, int $statusCode = Response::HTTP_OK): Response |
|
25
|
|
|
{ |
|
26
|
43 |
|
if (!is_object($data) && !is_array($data)) { |
|
27
|
1 |
|
throw new RuntimeException('Provided data for JSON response must be an object or an array'); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
42 |
|
return $this->buildJsonResponse($data, $statusCode, $this->getDefaultHeaders()); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
1 |
|
public function buildEmptyResponse(): Response |
|
34
|
|
|
{ |
|
35
|
1 |
|
return new Response('', Response::HTTP_NO_CONTENT, $this->getDefaultHeaders()); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
43 |
|
private function getDefaultHeaders() |
|
39
|
|
|
{ |
|
40
|
|
|
return [ |
|
41
|
43 |
|
'X-Frame-Options' => 'DENY', |
|
42
|
|
|
'Cache-Control' => 'must-revalidate, no-cache, no-store, private', |
|
43
|
|
|
]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
42 |
|
private function buildJsonResponse($data, int $statusCode, array $headers) |
|
47
|
|
|
{ |
|
48
|
|
|
try { |
|
49
|
42 |
|
$content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
|
50
|
1 |
|
} catch (Exception $exception) { |
|
51
|
|
|
if ( |
|
52
|
1 |
|
get_class($exception) === 'Exception' |
|
53
|
1 |
|
&& strpos($exception->getMessage(), 'Failed calling ') === 0 |
|
54
|
|
|
) { |
|
55
|
|
|
throw $exception->getPrevious() ?: $exception; |
|
56
|
|
|
} |
|
57
|
1 |
|
throw $exception; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
41 |
|
if (JSON_ERROR_NONE !== json_last_error()) { |
|
61
|
1 |
|
throw new InvalidArgumentException(json_last_error_msg()); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
40 |
|
return new Response($content, $statusCode, ['Content-Type' => 'application/json'] + $headers); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|