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
|
|
|
const PARAM_ID = 'id'; |
20
|
|
|
|
21
|
|
|
private static $queriesDefaultValue = [ |
22
|
|
|
self::PARAM_ID => null, |
23
|
|
|
self::PARAM_QUERY => null, |
24
|
|
|
self::PARAM_VARIABLES => null, |
25
|
|
|
]; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param Request $request |
29
|
|
|
* |
30
|
|
|
* @return array |
31
|
|
|
*/ |
32
|
|
|
public function parse(Request $request) |
33
|
|
|
{ |
34
|
|
|
// Extracts the GraphQL request parameters |
35
|
|
|
$queries = $this->getParsedBody($request); |
36
|
|
|
|
37
|
|
|
if (empty($queries)) { |
38
|
|
|
throw new BadRequestHttpException('Must provide at least one valid query.'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
foreach ($queries as $i => &$query) { |
42
|
|
|
$query = array_filter($query) + self::$queriesDefaultValue; |
43
|
|
|
|
44
|
|
|
if (!is_string($query[static::PARAM_QUERY])) { |
45
|
|
|
throw new BadRequestHttpException(sprintf('%s is not a valid query', json_encode($query[static::PARAM_QUERY]))); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $queries; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Gets the body from the request. |
54
|
|
|
* |
55
|
|
|
* @param Request $request |
56
|
|
|
* |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
|
|
private function getParsedBody(Request $request) |
60
|
|
|
{ |
61
|
|
|
$type = explode(';', $request->headers->get('content-type'))[0]; |
62
|
|
|
|
63
|
|
|
// JSON object |
64
|
|
|
if ($type !== static::CONTENT_TYPE_JSON) { |
65
|
|
|
throw new BadRequestHttpException(sprintf('Only request with content type "%s" is accepted.', static::CONTENT_TYPE_JSON)); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$parsedBody = json_decode($request->getContent(), true); |
69
|
|
|
|
70
|
|
|
if (JSON_ERROR_NONE !== json_last_error()) { |
71
|
|
|
throw new BadRequestHttpException('POST body sent invalid JSON'); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $parsedBody; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|