1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Overblog\GraphQLBundle\Request; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\Request; |
6
|
|
|
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; |
7
|
|
|
|
8
|
|
|
class BatchParser implements ParserInterface |
9
|
|
|
{ |
10
|
|
|
const PARAM_ID = 'id'; |
11
|
|
|
|
12
|
|
|
private static $queriesDefaultValue = [ |
13
|
|
|
self::PARAM_ID => null, |
14
|
|
|
self::PARAM_QUERY => null, |
15
|
|
|
self::PARAM_VARIABLES => null, |
16
|
|
|
]; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param Request $request |
20
|
|
|
* |
21
|
|
|
* @return array |
22
|
|
|
*/ |
23
|
|
|
public function parse(Request $request) |
24
|
|
|
{ |
25
|
|
|
// Extracts the GraphQL request parameters |
26
|
|
|
$queries = $this->getParsedBody($request); |
27
|
|
|
|
28
|
|
|
if (empty($queries)) { |
29
|
|
|
throw new BadRequestHttpException('Must provide at least one valid query.'); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
foreach ($queries as $i => &$query) { |
33
|
|
|
$query = array_filter($query) + self::$queriesDefaultValue; |
34
|
|
|
|
35
|
|
|
if (!is_string($query[static::PARAM_QUERY])) { |
36
|
|
|
throw new BadRequestHttpException(sprintf('%s is not a valid query', json_encode($query[static::PARAM_QUERY]))); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $queries; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Gets the body from the request. |
45
|
|
|
* |
46
|
|
|
* @param Request $request |
47
|
|
|
* |
48
|
|
|
* @return array |
49
|
|
|
*/ |
50
|
|
|
private function getParsedBody(Request $request) |
51
|
|
|
{ |
52
|
|
|
$type = explode(';', $request->headers->get('content-type'))[0]; |
53
|
|
|
|
54
|
|
|
// JSON object |
55
|
|
|
if ($type !== static::CONTENT_TYPE_JSON) { |
56
|
|
|
throw new BadRequestHttpException(sprintf('Only request with content type "%s" is accepted.', static::CONTENT_TYPE_JSON)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$parsedBody = json_decode($request->getContent(), true); |
60
|
|
|
|
61
|
|
|
if (JSON_ERROR_NONE !== json_last_error()) { |
62
|
|
|
throw new BadRequestHttpException('POST body sent invalid JSON'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $parsedBody; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|