Passed
Pull Request — master (#46)
by Markus
06:11
created

HandlesGraphqlRequests   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 329
Duplicated Lines 0 %

Test Coverage

Coverage 98.26%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 62
eloc 144
c 2
b 0
f 0
dl 0
loc 329
ccs 169
cts 172
cp 0.9826
rs 3.44

28 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeExecutionHook() 0 7 1
A __invoke() 0 43 2
A schemaPath() 0 3 1
B errorFormatter() 0 44 7
A reportException() 0 3 1
A debugFlags() 0 10 3
A decorateTypeConfig() 0 6 2
A schema() 0 3 1
A shouldDecorateWithResolveType() 0 4 2
A resolveClassName() 0 11 3
A namespace() 0 3 1
A fieldFromArray() 0 11 3
A queriesNamespace() 0 3 1
A typeFromArray() 0 4 3
A typesNamespace() 0 3 1
A decorateResponse() 0 6 3
A fieldFromObject() 0 11 2
A typeFromParentResolver() 0 8 3
A mutationsNamespace() 0 3 1
A propertyNames() 0 7 1
A resolveType() 0 6 1
A typeFromBaseClass() 0 4 2
A fieldFromResolver() 0 8 3
A make() 0 11 4
A typeFromObject() 0 4 2
A resolveFieldMethodName() 0 7 2
A resolveField() 0 14 4
A resolveTypeMethodName() 0 7 2

How to fix   Complexity   

Complex Class

Complex classes like HandlesGraphqlRequests often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use HandlesGraphqlRequests, and based on these observations, apply Extract Interface, too.

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
use Symfony\Component\HttpKernel\Exception\HttpException;
27
28
use function Amp\call;
29
30
trait HandlesGraphqlRequests
31
{
32
    private $classCache;
33
    private $namespaceCache;
34
35
    /**
36
     * Invoke the Graphql request handler.
37
     *
38
     * @param  \Illuminate\Http\Request  $request
39
     * @return array
40
     */
41 28
    public function __invoke(Request $request)
42
    {
43 28
        $this->classCache = [];
44 28
        $this->namespaceCache = null;
45
46 28
        $loader = app(DataLoader::class);
47
48 28
        $query = $request->input('query');
49 28
        $variables = $request->input('variables');
50 28
        $operationName = $request->input('operationName');
51
52
        try {
53 28
            $schema = BuildSchema::build($this->schema(), [$this, 'decorateTypeConfig']);
54
55 27
            $source = Parser::parse($query);
56
57 26
            $this->beforeExecutionHook($schema, $source, $operationName, $variables);
58
59
            /** @var \GraphQL\Executor\ExecutionResult */
60 26
            $result = null;
61
62 26
            GraphQL::promiseToExecute(
63 26
                app(PromiseAdapter::class),
64
                $schema,
65
                $source,
66 26
                null, // root
67 26
                compact('loader'), // context
68
                $variables,
69
                $operationName,
70 26
                [$this, 'resolveField'],
71 26
                null // validationRules
72 26
            )->then(function ($value) use (&$result) {
73 26
                $result = $value;
74 26
            });
75
76 26
            $loader->run();
77 2
        } catch (GraphqlError $e) {
78 2
            $result = new ExecutionResult(null, [$e]);
79
        }
80
81 28
        $result->setErrorFormatter([$this, 'errorFormatter']);
82
83 28
        return $this->decorateResponse($result->toArray($this->debugFlags()));
84
    }
85
86 25
    public function beforeExecutionHook(
87
        Schema $schema,
88
        DocumentNode $query,
89
        string $operationName = null,
90
        $variables = null
91
    ): void {
92 25
        return;
93
    }
94
95 13
    public function errorFormatter(GraphqlError $graphqlError)
96
    {
97 13
        $formattedError = FormattedError::createFromException($graphqlError);
98 13
        $throwable = $graphqlError->getPrevious();
99
100 13
        $this->reportException(
101 13
            $throwable instanceof Exception ? $throwable : $graphqlError
0 ignored issues
show
introduced by
$throwable is always a sub-type of Exception.
Loading history...
102
        );
103
104
        if (
105 13
            $throwable instanceof HttpException &&
106 13
            $throwable->getStatusCode() >= 400 &&
107 13
            $throwable->getStatusCode() < 500
108
        ) {
109 1
            return array_merge($formattedError, [
110 1
                'message' => $throwable->getMessage(),
111
                'extensions' => [
112 1
                    'category' => 'client',
113 1
                    'code' => $throwable->getStatusCode(),
114
                ],
115
            ]);
116
        }
117
118 12
        if ($throwable instanceof ModelNotFoundException) {
119 1
            return array_merge($formattedError, [
120 1
                'message' => class_basename($throwable->getModel()) . ' not found.',
121
                'extensions' => [
122
                    'category' => 'client',
123
                    'code' => 404,
124
                ],
125
            ]);
126
        }
127
128 11
        if ($throwable instanceof ValidationException) {
129 1
            return array_merge($formattedError, [
130 1
                'message' => $throwable->getMessage(),
131
                'extensions' => [
132 1
                    'category' => 'validation',
133 1
                    'validation' => $throwable->errors(),
134
                ],
135
            ]);
136
        }
137
138 10
        return $formattedError;
139
    }
140
141 13
    public function reportException(Exception $exception)
142
    {
143 13
        app(ExceptionHandler::class)->report($exception);
144 13
    }
145
146 26
    public function schema()
147
    {
148 26
        return file_get_contents($this->schemaPath());
149
    }
150
151 26
    public function schemaPath()
152
    {
153 26
        return config('butler.graphql.schema');
154
    }
155
156 27
    public function decorateTypeConfig(array $config, TypeDefinitionNode $typeDefinitionNode)
157
    {
158 27
        if ($this->shouldDecorateWithResolveType($typeDefinitionNode)) {
159 24
            $config['resolveType'] = [$this, 'resolveType'];
160
        }
161 27
        return $config;
162
    }
163
164 27
    protected function shouldDecorateWithResolveType(TypeDefinitionNode $typeDefinitionNode)
165
    {
166 27
        return $typeDefinitionNode instanceof InterfaceTypeDefinitionNode
167 27
            || $typeDefinitionNode instanceof UnionTypeDefinitionNode;
168
    }
169
170 28
    public function debugFlags()
171
    {
172 28
        $flags = 0;
173 28
        if (config('butler.graphql.include_debug_message')) {
174 8
            $flags |= DebugFlag::INCLUDE_DEBUG_MESSAGE;
175
        }
176 28
        if (config('butler.graphql.include_trace')) {
177 3
            $flags |= DebugFlag::INCLUDE_TRACE;
178
        }
179 28
        return $flags;
180
    }
181
182 25
    public function resolveField($source, $args, $context, ResolveInfo $info)
183
    {
184 25
        $field = $this->fieldFromResolver($source, $args, $context, $info)
185 10
            ?? $this->fieldFromArray($source, $args, $context, $info)
186 15
            ?? $this->fieldFromObject($source, $args, $context, $info);
187
188 15
        return call(static function () use ($field, $source, $args, $context, $info) {
189 15
            if (function_exists('enum_exists') && $field instanceof \BackedEnum) {
0 ignored issues
show
Bug introduced by
The type BackedEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
190
                return $field->value;
191
            }
192
193 15
            return $field instanceof \Closure
194 1
                ? $field($source, $args, $context, $info)
195 15
                : $field;
196 15
        });
197
    }
198
199 4
    public function resolveType($source, $context, ResolveInfo $info)
200
    {
201 4
        return $this->typeFromArray($source, $context, $info)
202 4
            ?? $this->typeFromObject($source, $context, $info)
203 4
            ?? $this->typeFromParentResolver($source, $context, $info)
204 4
            ?? $this->typeFromBaseClass($source, $context, $info);
205
    }
206
207 25
    public function fieldFromResolver($source, $args, $context, ResolveInfo $info)
208
    {
209 25
        $className = $this->resolveClassName($info);
210 25
        $methodName = $this->resolveFieldMethodName($info);
211
212 25
        if ($resolver = $this->make($className)) {
213 24
            if (method_exists($resolver, $methodName)) {
214 24
                return $resolver->{$methodName}($source, $args, $context, $info);
215
            }
216
        }
217 10
    }
218
219 10
    public function fieldFromArray($source, $args, $context, ResolveInfo $info)
220
    {
221 10
        if (is_array($source) || $source instanceof \ArrayAccess) {
222 8
            return collect($this->propertyNames($info))
223 8
                ->map(function ($propertyName) use ($source) {
224 8
                    return $source[$propertyName] ?? null;
225 8
                })
226 8
                ->reject(function ($value) {
227 8
                    return is_null($value);
228 8
                })
229 8
                ->first();
230
        }
231 7
    }
232
233 7
    public function fieldFromObject($source, $args, $context, ResolveInfo $info)
234
    {
235 7
        if (is_object($source)) {
236 7
            return collect($this->propertyNames($info))
237 7
                ->map(function ($propertyName) use ($source) {
238 7
                    return $source->{$propertyName} ?? null;
239 7
                })
240 7
                ->reject(function ($value) {
241 7
                    return is_null($value);
242 7
                })
243 7
                ->first();
244
        }
245 1
    }
246
247 4
    public function typeFromArray($source, $context, ResolveInfo $info)
248
    {
249 4
        if (is_array($source) || $source instanceof \ArrayAccess) {
250 4
            return $source['__typename'] ?? null;
251
        }
252 2
    }
253
254 4
    public function typeFromObject($source, $context, ResolveInfo $info)
255
    {
256 4
        if (is_object($source)) {
257 2
            return $source->__typename ?? null;
258
        }
259 4
    }
260
261 4
    public function typeFromParentResolver($source, $context, ResolveInfo $info)
262
    {
263 4
        $className = $this->resolveClassName($info);
264 4
        $methodName = $this->resolveTypeMethodName($info);
265
266 4
        if ($resolver = $this->make($className)) {
267 4
            if (method_exists($resolver, $methodName)) {
268 4
                return $resolver->{$methodName}($source, $context, $info);
269
            }
270
        }
271
    }
272
273 1
    public function typeFromBaseClass($source, $context, ResolveInfo $info)
274
    {
275 1
        if (is_object($source)) {
276 1
            return class_basename($source);
277
        }
278
    }
279
280 10
    public function propertyNames(ResolveInfo $info): array
281
    {
282 10
        return collect([
283 10
            Str::snake($info->fieldName),
284 10
            Str::camel($info->fieldName),
285 10
            Str::kebab(Str::camel($info->fieldName)),
286 10
        ])->unique()->toArray();
287
    }
288
289 25
    protected function resolveClassName(ResolveInfo $info): string
290
    {
291 25
        if ($info->parentType->name === 'Query') {
292 24
            return $this->queriesNamespace() . Str::studly($info->fieldName);
293
        }
294
295 11
        if ($info->parentType->name === 'Mutation') {
296 1
            return $this->mutationsNamespace() . Str::studly($info->fieldName);
297
        }
298
299 11
        return $this->typesNamespace() . Str::studly($info->parentType->name);
300
    }
301
302 25
    public function resolveFieldMethodName(ResolveInfo $info): string
303
    {
304 25
        if (in_array($info->parentType->name, ['Query', 'Mutation'])) {
305 25
            return '__invoke';
306
        }
307
308 11
        return Str::camel($info->fieldName);
309
    }
310
311 4
    public function resolveTypeMethodName(ResolveInfo $info): string
312
    {
313 4
        if (in_array($info->parentType->name, ['Query', 'Mutation'])) {
314 2
            return 'resolveType';
315
        }
316
317 2
        return 'resolveTypeFor' . ucfirst(Str::camel($info->fieldName));
318
    }
319
320 25
    public function namespace(): string
321
    {
322 25
        return $this->namespaceCache ?? $this->namespaceCache = config('butler.graphql.namespace');
323
    }
324
325 24
    public function queriesNamespace(): string
326
    {
327 24
        return $this->namespace() . 'Queries\\';
328
    }
329
330 1
    public function mutationsNamespace(): string
331
    {
332 1
        return $this->namespace() . 'Mutations\\';
333
    }
334
335 11
    public function typesNamespace(): string
336
    {
337 11
        return $this->namespace() . 'Types\\';
338
    }
339
340 28
    public function decorateResponse(array $data): array
341
    {
342 28
        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

342
        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...
343 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

343
            $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...
344
        }
345 28
        return $data;
346
    }
347
348 25
    protected function make(string $className)
349
    {
350 25
        if (array_key_exists($className, $this->classCache)) {
351 10
            return $this->classCache[$className];
352
        }
353
354 25
        $class = app()->has($className) || class_exists($className)
355 25
            ? app($className)
356 24
            : null;
357
358 24
        return $this->classCache[$className] = $class;
359
    }
360
}
361