Passed
Push — master ( 65c987...0da507 )
by
unknown
06:14
created

HandlesGraphqlRequests::make()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 10
cc 4
nc 5
nop 1
crap 4
1
<?php
2
3
namespace Butler\Graphql\Concerns;
4
5
use Butler\Graphql\DataLoader;
6
use Exception;
7
use GraphQL\Error\DebugFlag;
8
use GraphQL\Error\Error as GraphqlError;
9
use GraphQL\Error\FormattedError;
10
use GraphQL\Executor\ExecutionResult;
11
use GraphQL\Executor\Promise\PromiseAdapter;
12
use GraphQL\GraphQL;
13
use GraphQL\Language\AST\DocumentNode;
14
use GraphQL\Language\AST\InterfaceTypeDefinitionNode;
15
use GraphQL\Language\AST\TypeDefinitionNode;
16
use GraphQL\Language\AST\UnionTypeDefinitionNode;
17
use GraphQL\Language\Parser;
18
use GraphQL\Type\Definition\ResolveInfo;
19
use GraphQL\Type\Schema;
20
use GraphQL\Utils\BuildSchema;
21
use Illuminate\Contracts\Debug\ExceptionHandler;
22
use Illuminate\Database\Eloquent\ModelNotFoundException;
23
use Illuminate\Http\Request;
24
use Illuminate\Support\Str;
25
use Illuminate\Validation\ValidationException;
26
27
use function Amp\call;
28
29
trait HandlesGraphqlRequests
30
{
31
    private $classCache;
32
    private $namespaceCache;
33
34
    /**
35
     * Invoke the Graphql request handler.
36
     *
37
     * @param  \Illuminate\Http\Request  $request
38
     * @return array
39
     */
40 26
    public function __invoke(Request $request)
41
    {
42 26
        $this->classCache = [];
43 26
        $this->namespaceCache = null;
44
45 26
        $loader = app(DataLoader::class);
46
47 26
        $query = $request->input('query');
48 26
        $variables = $request->input('variables');
49 26
        $operationName = $request->input('operationName');
50
51
        try {
52 26
            $schema = BuildSchema::build($this->schema(), [$this, 'decorateTypeConfig']);
53
54 25
            $source = Parser::parse($query);
55
56 24
            $this->beforeExecutionHook($schema, $source, $operationName, $variables);
57
58
            /** @var \GraphQL\Executor\ExecutionResult */
59 24
            $result = null;
60
61 24
            GraphQL::promiseToExecute(
62 24
                app(PromiseAdapter::class),
63
                $schema,
64
                $source,
65 24
                null, // root
66 24
                compact('loader'), // context
67
                $variables,
68
                $operationName,
69 24
                [$this, 'resolveField'],
70 24
                null // validationRules
71 24
            )->then(function ($value) use (&$result) {
72 24
                $result = $value;
73 24
            });
74
75 24
            $loader->run();
76 2
        } catch (GraphqlError $e) {
77 2
            $result = new ExecutionResult(null, [$e]);
78
        }
79
80 26
        $result->setErrorFormatter([$this, 'errorFormatter']);
81
82 26
        return $this->decorateResponse($result->toArray($this->debugFlags()));
83
    }
84
85 23
    public function beforeExecutionHook(
86
        Schema $schema,
87
        DocumentNode $query,
88
        string $operationName = null,
89
        $variables = null
90
    ): void {
91 23
        return;
92
    }
93
94 11
    public function errorFormatter(GraphqlError $graphqlError)
95
    {
96 11
        $formattedError = FormattedError::createFromException($graphqlError);
97 11
        $throwable = $graphqlError->getPrevious();
98
99 11
        $this->reportException(
100 11
            $throwable instanceof Exception ? $throwable : $graphqlError
0 ignored issues
show
introduced by
$throwable is always a sub-type of Exception.
Loading history...
101
        );
102
103 11
        if ($throwable instanceof ModelNotFoundException) {
104 1
            return array_merge($formattedError, [
105 1
                'message' => class_basename($throwable->getModel()) . ' not found.',
106
                'extensions' => [
107
                    'category' => 'client',
108
                ],
109
            ]);
110
        }
111
112 10
        if ($throwable instanceof ValidationException) {
113 1
            return array_merge($formattedError, [
114 1
                'message' => $throwable->getMessage(),
115
                'extensions' => [
116 1
                    'category' => 'validation',
117 1
                    'validation' => $throwable->errors(),
118
                ],
119
            ]);
120
        }
121
122 9
        return $formattedError;
123
    }
124
125 11
    public function reportException(Exception $exception)
126
    {
127 11
        app(ExceptionHandler::class)->report($exception);
128 11
    }
129
130 24
    public function schema()
131
    {
132 24
        return file_get_contents($this->schemaPath());
133
    }
134
135 24
    public function schemaPath()
136
    {
137 24
        return config('butler.graphql.schema');
138
    }
139
140 25
    public function decorateTypeConfig(array $config, TypeDefinitionNode $typeDefinitionNode)
141
    {
142 25
        if ($this->shouldDecorateWithResolveType($typeDefinitionNode)) {
143 22
            $config['resolveType'] = [$this, 'resolveType'];
144
        }
145 25
        return $config;
146
    }
147
148 25
    protected function shouldDecorateWithResolveType(TypeDefinitionNode $typeDefinitionNode)
149
    {
150 25
        return $typeDefinitionNode instanceof InterfaceTypeDefinitionNode
151 25
            || $typeDefinitionNode instanceof UnionTypeDefinitionNode;
152
    }
153
154 26
    public function debugFlags()
155
    {
156 26
        $flags = 0;
157 26
        if (config('butler.graphql.include_debug_message')) {
158 8
            $flags |= DebugFlag::INCLUDE_DEBUG_MESSAGE;
159
        }
160 26
        if (config('butler.graphql.include_trace')) {
161 3
            $flags |= DebugFlag::INCLUDE_TRACE;
162
        }
163 26
        return $flags;
164
    }
165
166 23
    public function resolveField($source, $args, $context, ResolveInfo $info)
167
    {
168 23
        $field = $this->fieldFromResolver($source, $args, $context, $info)
169 10
            ?? $this->fieldFromArray($source, $args, $context, $info)
170 15
            ?? $this->fieldFromObject($source, $args, $context, $info);
171
172 15
        return call(static function () use ($field, $source, $args, $context, $info) {
173 15
            return $field instanceof \Closure
174 1
                ? $field($source, $args, $context, $info)
175 15
                : $field;
176 15
        });
177
    }
178
179 4
    public function resolveType($source, $context, ResolveInfo $info)
180
    {
181 4
        return $this->typeFromArray($source, $context, $info)
182 4
            ?? $this->typeFromObject($source, $context, $info)
183 4
            ?? $this->typeFromParentResolver($source, $context, $info)
184 4
            ?? $this->typeFromBaseClass($source, $context, $info);
185
    }
186
187 23
    public function fieldFromResolver($source, $args, $context, ResolveInfo $info)
188
    {
189 23
        $className = $this->resolveClassName($info);
190 23
        $methodName = $this->resolveFieldMethodName($info);
191
192 23
        if ($resolver = $this->make($className)) {
193 22
            if (method_exists($resolver, $methodName)) {
194 22
                return $resolver->{$methodName}($source, $args, $context, $info);
195
            }
196
        }
197 10
    }
198
199 10
    public function fieldFromArray($source, $args, $context, ResolveInfo $info)
200
    {
201 10
        if (is_array($source) || $source instanceof \ArrayAccess) {
202 8
            return collect($this->propertyNames($info))
203 8
                ->map(function ($propertyName) use ($source) {
204 8
                    return $source[$propertyName] ?? null;
205 8
                })
206 8
                ->reject(function ($value) {
207 8
                    return is_null($value);
208 8
                })
209 8
                ->first();
210
        }
211 7
    }
212
213 7
    public function fieldFromObject($source, $args, $context, ResolveInfo $info)
214
    {
215 7
        if (is_object($source)) {
216 7
            return collect($this->propertyNames($info))
217 7
                ->map(function ($propertyName) use ($source) {
218 7
                    return $source->{$propertyName} ?? null;
219 7
                })
220 7
                ->reject(function ($value) {
221 7
                    return is_null($value);
222 7
                })
223 7
                ->first();
224
        }
225 1
    }
226
227 4
    public function typeFromArray($source, $context, ResolveInfo $info)
228
    {
229 4
        if (is_array($source) || $source instanceof \ArrayAccess) {
230 4
            return $source['__typename'] ?? null;
231
        }
232 2
    }
233
234 4
    public function typeFromObject($source, $context, ResolveInfo $info)
235
    {
236 4
        if (is_object($source)) {
237 2
            return $source->__typename ?? null;
238
        }
239 4
    }
240
241 4
    public function typeFromParentResolver($source, $context, ResolveInfo $info)
242
    {
243 4
        $className = $this->resolveClassName($info);
244 4
        $methodName = $this->resolveTypeMethodName($info);
245
246 4
        if ($resolver = $this->make($className)) {
247 4
            if (method_exists($resolver, $methodName)) {
248 4
                return $resolver->{$methodName}($source, $context, $info);
249
            }
250
        }
251
    }
252
253 1
    public function typeFromBaseClass($source, $context, ResolveInfo $info)
254
    {
255 1
        if (is_object($source)) {
256 1
            return class_basename($source);
257
        }
258
    }
259
260 10
    public function propertyNames(ResolveInfo $info): array
261
    {
262 10
        return collect([
263 10
            Str::snake($info->fieldName),
264 10
            Str::camel($info->fieldName),
265 10
            Str::kebab(Str::camel($info->fieldName)),
266 10
        ])->unique()->toArray();
267
    }
268
269 23
    protected function resolveClassName(ResolveInfo $info): string
270
    {
271 23
        if ($info->parentType->name === 'Query') {
272 22
            return $this->queriesNamespace() . Str::studly($info->fieldName);
273
        }
274
275 11
        if ($info->parentType->name === 'Mutation') {
276 1
            return $this->mutationsNamespace() . Str::studly($info->fieldName);
277
        }
278
279 11
        return $this->typesNamespace() . Str::studly($info->parentType->name);
280
    }
281
282 23
    public function resolveFieldMethodName(ResolveInfo $info): string
283
    {
284 23
        if (in_array($info->parentType->name, ['Query', 'Mutation'])) {
285 23
            return '__invoke';
286
        }
287
288 11
        return Str::camel($info->fieldName);
289
    }
290
291 4
    public function resolveTypeMethodName(ResolveInfo $info): string
292
    {
293 4
        if (in_array($info->parentType->name, ['Query', 'Mutation'])) {
294 2
            return 'resolveType';
295
        }
296
297 2
        return 'resolveTypeFor' . ucfirst(Str::camel($info->fieldName));
298
    }
299
300 23
    public function namespace(): string
301
    {
302 23
        return $this->namespaceCache ?? $this->namespaceCache = config('butler.graphql.namespace');
303
    }
304
305 22
    public function queriesNamespace(): string
306
    {
307 22
        return $this->namespace() . 'Queries\\';
308
    }
309
310 1
    public function mutationsNamespace(): string
311
    {
312 1
        return $this->namespace() . 'Mutations\\';
313
    }
314
315 11
    public function typesNamespace(): string
316
    {
317 11
        return $this->namespace() . 'Types\\';
318
    }
319
320 26
    public function decorateResponse(array $data): array
321
    {
322 26
        if (app()->bound('debugbar') && app('debugbar')->isEnabled()) {
0 ignored issues
show
Bug introduced by
The method isEnabled() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

322
        if (app()->bound('debugbar') && app('debugbar')->/** @scrutinizer ignore-call */ isEnabled()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
323 1
            $data['debug'] = app('debugbar')->getData();
0 ignored issues
show
Bug introduced by
The method getData() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

323
            $data['debug'] = app('debugbar')->/** @scrutinizer ignore-call */ getData();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
324
        }
325 26
        return $data;
326
    }
327
328 23
    protected function make(string $className)
329
    {
330 23
        if (array_key_exists($className, $this->classCache)) {
331 10
            return $this->classCache[$className];
332
        }
333
334 23
        $class = app()->has($className) || class_exists($className)
335 23
            ? app($className)
336 22
            : null;
337
338 22
        return $this->classCache[$className] = $class;
339
    }
340
}
341