Passed
Pull Request — master (#3041)
by
unknown
04:33
created

EntrypointAction::parseInput()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 12
nop 4
dl 0
loc 17
rs 9.6111
c 0
b 0
f 0
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\Executor\ExecutionResult;
21
use Symfony\Component\HttpFoundation\JsonResponse;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
25
26
/**
27
 * GraphQL API entrypoint.
28
 *
29
 * @author Alan Poulain <[email protected]>
30
 */
31
final class EntrypointAction
32
{
33
    private $schemaBuilder;
34
    private $executor;
35
    private $graphiQlAction;
36
    private $graphQlPlaygroundAction;
37
    private $debug;
38
    private $graphiqlEnabled;
39
    private $graphQlPlaygroundEnabled;
40
    private $defaultIde;
41
    private $propertyAccessor;
42
43
    public function __construct(SchemaBuilderInterface $schemaBuilder, ExecutorInterface $executor, GraphiQlAction $graphiQlAction, GraphQlPlaygroundAction $graphQlPlaygroundAction, PropertyAccessorInterface $propertyAccessor, 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
        $this->propertyAccessor = $propertyAccessor;
54
    }
55
56
    public function __invoke(Request $request): Response
57
    {
58
        if ($request->isMethod('GET') && 'html' === $request->getRequestFormat()) {
59
            if ('graphiql' === $this->defaultIde && $this->graphiqlEnabled) {
60
                return ($this->graphiQlAction)($request);
61
            }
62
63
            if ('graphql-playground' === $this->defaultIde && $this->graphQlPlaygroundEnabled) {
64
                return ($this->graphQlPlaygroundAction)($request);
65
            }
66
        }
67
68
        [$query, $operation, $variables] = $this->parseRequest($request);
69
70
        if (null === $query) {
71
            return new JsonResponse(new ExecutionResult(null, [new Error('GraphQL query is not valid')]), Response::HTTP_BAD_REQUEST);
72
        }
73
74
        if (null === $variables) {
75
            return new JsonResponse(new ExecutionResult(null, [new Error('GraphQL variables are not valid JSON')]), Response::HTTP_BAD_REQUEST);
76
        }
77
78
        try {
79
            $executionResult = $this->executor->executeQuery($this->schemaBuilder->getSchema(), $query, null, null, $variables, $operation);
80
        } catch (\Exception $e) {
81
            $executionResult = new ExecutionResult(null, [new Error($e->getMessage(), null, null, null, null, $e)]);
82
        }
83
84
        return new JsonResponse($executionResult->toArray($this->debug));
85
    }
86
87
    private function parseRequest(Request $request): array
88
    {
89
        $query = $request->query->get('query');
90
        $operation = $request->query->get('operation');
91
        if ($variables = $request->query->get('variables', [])) {
92
            $variables = json_decode($variables, true);
93
        }
94
95
        if (!$request->isMethod('POST')) {
96
            return [$query, $operation, $variables];
97
        }
98
99
        if ('json' === $request->getContentType()) {
100
            return $this->parseInput($query, $variables, $operation, $request->getContent());
101
        }
102
103
        if (false !== mb_stripos($request->headers->get('CONTENT_TYPE'), 'multipart/form-data')) {
104
            if ($request->request->has('operations')) {
105
                [$query, $operation, $variables] = $this->parseInput($query, $variables, $operation, $request->request->get('operations'));
106
107
                if ($request->request->has('map')) {
108
                    $variables = $this->applyMapToVariables($request, $variables);
109
                }
110
111
                return [$query, $operation, $variables];
112
            }
113
        }
114
115
        if ('application/graphql' === $request->headers->get('CONTENT_TYPE')) {
116
            $query = $request->getContent();
117
        }
118
119
        return [$query, $operation, $variables];
120
    }
121
122
    private function parseInput(?string $query, ?array $variables, ?string $operation, string $jsonContent): array
123
    {
124
        $input = json_decode($jsonContent, true);
125
126
        if (isset($input['query'])) {
127
            $query = $input['query'];
128
        }
129
130
        if (isset($input['variables'])) {
131
            $variables = \is_array($input['variables']) ? $input['variables'] : json_decode($input['variables'], true);
132
        }
133
134
        if (isset($input['operation'])) {
135
            $operation = $input['operation'];
136
        }
137
138
        return [$query, $operation, $variables];
139
    }
140
141
    private function applyMapToVariables(Request $request, array $variables): array
142
    {
143
        $mapValues = json_decode($request->request->get('map'), true);
144
        if (!$mapValues) {
145
            return $variables;
146
        }
147
        foreach ($mapValues as $key => $value) {
148
            if ($request->files->has($key)) {
149
                foreach ($mapValues[$key] as $mapValue) {
150
                    $path = explode('.', $mapValue);
151
                    if ('variables' === $path[0]) {
152
                        unset($path[0]);
153
                        $this->propertyAccessor->setValue($variables, '['.implode('][', $path).']', $request->files->get($key));
154
                    }
155
                }
156
            }
157
        }
158
159
        return $variables;
160
    }
161
}
162