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