Passed
Push — master ( 336684...81d276 )
by Kévin
19:58 queued 14:43
created

EntrypointAction::parseData()   A

Complexity

Conditions 6
Paths 13

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 9
c 0
b 0
f 0
nc 13
nop 4
dl 0
loc 19
rs 9.2222
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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 ApiPlatform\Core\GraphQl\Action;
15
16
use ApiPlatform\Core\GraphQl\ExecutorInterface;
17
use ApiPlatform\Core\GraphQl\Type\SchemaBuilderInterface;
18
use GraphQL\Error\Debug;
19
use GraphQL\Error\Error;
20
use GraphQL\Error\UserError;
21
use GraphQL\Executor\ExecutionResult;
22
use Symfony\Component\HttpFoundation\JsonResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
26
27
/**
28
 * GraphQL API entrypoint.
29
 *
30
 * @author Alan Poulain <[email protected]>
31
 */
32
final class EntrypointAction
33
{
34
    private $schemaBuilder;
35
    private $executor;
36
    private $graphiQlAction;
37
    private $graphQlPlaygroundAction;
38
    private $debug;
39
    private $graphiqlEnabled;
40
    private $graphQlPlaygroundEnabled;
41
    private $defaultIde;
42
43
    public function __construct(SchemaBuilderInterface $schemaBuilder, ExecutorInterface $executor, GraphiQlAction $graphiQlAction, GraphQlPlaygroundAction $graphQlPlaygroundAction, bool $debug = false, bool $graphiqlEnabled = false, bool $graphQlPlaygroundEnabled = false, $defaultIde = false)
44
    {
45
        $this->schemaBuilder = $schemaBuilder;
46
        $this->executor = $executor;
47
        $this->graphiQlAction = $graphiQlAction;
48
        $this->graphQlPlaygroundAction = $graphQlPlaygroundAction;
49
        $this->debug = $debug ? Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE : false;
50
        $this->graphiqlEnabled = $graphiqlEnabled;
51
        $this->graphQlPlaygroundEnabled = $graphQlPlaygroundEnabled;
52
        $this->defaultIde = $defaultIde;
53
    }
54
55
    public function __invoke(Request $request): Response
56
    {
57
        if ($request->isMethod('GET') && 'html' === $request->getRequestFormat()) {
58
            if ('graphiql' === $this->defaultIde && $this->graphiqlEnabled) {
59
                return ($this->graphiQlAction)($request);
60
            }
61
62
            if ('graphql-playground' === $this->defaultIde && $this->graphQlPlaygroundEnabled) {
63
                return ($this->graphQlPlaygroundAction)($request);
64
            }
65
        }
66
67
        try {
68
            [$query, $operation, $variables] = $this->parseRequest($request);
69
            if (null === $query) {
70
                throw new BadRequestHttpException('GraphQL query is not valid.');
71
            }
72
73
            $executionResult = $this->executor->executeQuery($this->schemaBuilder->getSchema(), $query, null, null, $variables, $operation);
74
        } catch (BadRequestHttpException $e) {
75
            $exception = new UserError($e->getMessage(), 0, $e);
76
77
            return $this->buildExceptionResponse($exception, Response::HTTP_BAD_REQUEST);
78
        } catch (\Exception $e) {
79
            return $this->buildExceptionResponse($e, Response::HTTP_OK);
80
        }
81
82
        return new JsonResponse($executionResult->toArray($this->debug));
83
    }
84
85
    /**
86
     * @throws BadRequestHttpException
87
     */
88
    private function parseRequest(Request $request): array
89
    {
90
        $query = $request->query->get('query');
91
        $operation = $request->query->get('operation');
92
        if ($variables = $request->query->get('variables', [])) {
93
            $variables = $this->decodeVariables($variables);
94
        }
95
96
        if (!$request->isMethod('POST')) {
97
            return [$query, $operation, $variables];
98
        }
99
100
        if ('json' === $request->getContentType()) {
101
            return $this->parseData($query, $operation, $variables, $request->getContent());
102
        }
103
104
        if ('graphql' === $request->getContentType()) {
105
            $query = $request->getContent();
106
        }
107
108
        if ('multipart' === $request->getContentType()) {
109
            return $this->parseMultipartRequest($query, $operation, $variables, $request->request->all(), $request->files->all());
110
        }
111
112
        return [$query, $operation, $variables];
113
    }
114
115
    /**
116
     * @throws BadRequestHttpException
117
     */
118
    private function parseData(?string $query, ?string $operation, array $variables, string $jsonContent): array
119
    {
120
        if (!\is_array($data = json_decode($jsonContent, true))) {
121
            throw new BadRequestHttpException('GraphQL data is not valid JSON.');
122
        }
123
124
        if (isset($data['query'])) {
125
            $query = $data['query'];
126
        }
127
128
        if (isset($data['variables'])) {
129
            $variables = \is_array($data['variables']) ? $data['variables'] : $this->decodeVariables($data['variables']);
130
        }
131
132
        if (isset($data['operation'])) {
133
            $operation = $data['operation'];
134
        }
135
136
        return [$query, $operation, $variables];
137
    }
138
139
    /**
140
     * @throws BadRequestHttpException
141
     */
142
    private function parseMultipartRequest(?string $query, ?string $operation, array $variables, array $bodyParameters, array $files): array
143
    {
144
        /** @var string $operations */
145
        /** @var string $map */
146
        if ((null === $operations = $bodyParameters['operations'] ?? null) || (null === $map = $bodyParameters['map'] ?? null)) {
147
            throw new BadRequestHttpException('GraphQL multipart request does not respect the specification.');
148
        }
149
150
        [$query, $operation, $variables] = $this->parseData($query, $operation, $variables, $operations);
151
152
        if (!\is_array($decodedMap = json_decode($map, true))) {
153
            throw new BadRequestHttpException('GraphQL multipart request map is not valid JSON.');
154
        }
155
156
        $variables = $this->applyMapToVariables($decodedMap, $variables, $files);
157
158
        return [$query, $operation, $variables];
159
    }
160
161
    /**
162
     * @throws BadRequestHttpException
163
     */
164
    private function applyMapToVariables(array $map, array $variables, array $files): array
165
    {
166
        foreach ($map as $key => $value) {
167
            if (null === $file = $files[$key] ?? null) {
168
                throw new BadRequestHttpException('GraphQL multipart request file has not been sent correctly.');
169
            }
170
171
            foreach ($map[$key] as $mapValue) {
172
                $path = explode('.', $mapValue);
173
174
                if ('variables' !== $path[0]) {
175
                    throw new BadRequestHttpException('GraphQL multipart request path in map is invalid.');
176
                }
177
178
                unset($path[0]);
179
180
                $mapPathExistsInVariables = array_reduce($path, static function (array $inVariables, string $pathElement) {
181
                    return \array_key_exists($pathElement, $inVariables) ? $inVariables[$pathElement] : false;
182
                }, $variables);
183
184
                if (false === $mapPathExistsInVariables) {
185
                    throw new BadRequestHttpException('GraphQL multipart request path in map does not match the variables.');
186
                }
187
188
                $variableFileValue = &$variables;
189
                foreach ($path as $pathValue) {
190
                    $variableFileValue = &$variableFileValue[$pathValue];
191
                }
192
                $variableFileValue = $file;
193
            }
194
        }
195
196
        return $variables;
197
    }
198
199
    /**
200
     * @throws BadRequestHttpException
201
     */
202
    private function decodeVariables(string $variables): array
203
    {
204
        if (!\is_array($variables = json_decode($variables, true))) {
205
            throw new BadRequestHttpException('GraphQL variables are not valid JSON.');
206
        }
207
208
        return $variables;
209
    }
210
211
    private function buildExceptionResponse(\Exception $e, int $statusCode): JsonResponse
212
    {
213
        $executionResult = new ExecutionResult(null, [new Error($e->getMessage(), null, null, null, null, $e)]);
214
215
        return new JsonResponse($executionResult->toArray($this->debug), $statusCode);
216
    }
217
}
218