Passed
Push — master ( bbbc92...3440da )
by Markus
05:59
created

HandlesGraphqlRequests   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 325
Duplicated Lines 0 %

Test Coverage

Coverage 98.82%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 60
eloc 142
c 2
b 0
f 0
dl 0
loc 325
ccs 168
cts 170
cp 0.9882
rs 3.6

28 Methods

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

338
        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...
339 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

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