Completed
Pull Request — master (#76)
by Sebastian
04:15
created

Processor::walkQuery()   C

Complexity

Conditions 15
Paths 4

Size

Total Lines 53
Code Lines 33

Duplication

Lines 18
Ratio 33.96 %

Code Coverage

Tests 32
CRAP Score 15.0062

Importance

Changes 0
Metric Value
dl 18
loc 53
ccs 32
cts 33
cp 0.9697
rs 6.2939
c 0
b 0
f 0
cc 15
eloc 33
nc 4
nop 2
crap 15.0062

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
* This file is a part of graphql-youshido project.
4
*
5
* @author Portey Vasil <[email protected]>
6
* @author Alexandr Viniychuk <[email protected]>
7
* created: 11/28/15 1:05 AM
8
*/
9
10
namespace Youshido\GraphQL\Execution;
11
12
use Youshido\GraphQL\Execution\Container\Container;
13
use Youshido\GraphQL\Execution\Context\ExecutionContext;
14
use Youshido\GraphQL\Execution\Visitor\AbstractQueryVisitor;
15
use Youshido\GraphQL\Execution\Visitor\MaxComplexityQueryVisitor;
16
use Youshido\GraphQL\Field\Field;
17
use Youshido\GraphQL\Field\FieldInterface;
18
use Youshido\GraphQL\Parser\Ast\Field as FieldAst;
19
use Youshido\GraphQL\Parser\Ast\Fragment;
20
use Youshido\GraphQL\Parser\Ast\FragmentInterface;
21
use Youshido\GraphQL\Parser\Ast\FragmentReference;
22
use Youshido\GraphQL\Parser\Ast\Mutation;
23
use Youshido\GraphQL\Parser\Ast\Query;
24
use Youshido\GraphQL\Parser\Ast\TypedFragmentReference;
25
use Youshido\GraphQL\Parser\Parser;
26
use Youshido\GraphQL\Schema\AbstractSchema;
27
use Youshido\GraphQL\Type\AbstractType;
28
use Youshido\GraphQL\Type\Object\AbstractObjectType;
29
use Youshido\GraphQL\Type\TypeInterface;
30
use Youshido\GraphQL\Type\TypeMap;
31
use Youshido\GraphQL\Type\TypeService;
32
use Youshido\GraphQL\Type\Union\AbstractUnionType;
33
use Youshido\GraphQL\Validator\Exception\ResolveException;
34
use Youshido\GraphQL\Validator\RequestValidator\RequestValidator;
35
use Youshido\GraphQL\Validator\ResolveValidator\ResolveValidator;
36
use Youshido\GraphQL\Validator\ResolveValidator\ResolveValidatorInterface;
37
38
class Processor
39
{
40
41
    const TYPE_NAME_QUERY = '__typename';
42
43
    /** @var  array */
44
    protected $data;
45
46
    /** @var ResolveValidatorInterface */
47
    protected $resolveValidator;
48
49
    /** @var ExecutionContext */
50
    protected $executionContext;
51
52
    /** @var int */
53
    protected $maxComplexity;
54
55 31
    public function __construct(AbstractSchema $schema)
56
    {
57
        /**
58
         * This will be removed in 1.4 when __construct signature is changed to accept ExecutionContext
59
         */
60 31
        if (empty($this->executionContext)) {
61 31
            $this->executionContext = new ExecutionContext($schema);
62 31
            $this->executionContext->setContainer(new Container());
63
        }
64 31
        $this->resolveValidator = new ResolveValidator($this->executionContext);
65 31
    }
66
67 29
    public function processPayload($payload, $variables = [], $reducers = [])
68
    {
69 29
        $this->data = [];
70
71
        try {
72 29
            $this->parseAndCreateRequest($payload, $variables);
73
74 29
            $queryType    = $this->executionContext->getSchema()->getQueryType();
75 29
            $mutationType = $this->executionContext->getSchema()->getMutationType();
76
77 29
            if ($this->maxComplexity) {
78 1
                $reducers[] = new MaxComplexityQueryVisitor($this->maxComplexity);
79
            }
80
81 29
            $this->reduceQuery($queryType, $mutationType, $reducers);
82
83 29
            foreach ($this->executionContext->getRequest()->getOperationsInOrder() as $operation) {
84 29
                if ($operationResult = $this->executeOperation($operation, $operation instanceof Mutation ? $mutationType : $queryType)) {
85 29
                    $this->data = array_merge($this->data, $operationResult);
86
                };
87
            }
88
89 4
        } catch (\Exception $e) {
90 4
            $this->executionContext->addError($e);
91
        }
92
93 29
        return $this;
94
    }
95
96 29
    protected function parseAndCreateRequest($payload, $variables = [])
97
    {
98 29
        if (empty($payload)) {
99 1
            throw new \Exception('Must provide an operation.');
100
        }
101
102 29
        $parser  = new Parser();
103 29
        $request = new Request($parser->parse($payload), $variables);
104
105 29
        (new RequestValidator())->validate($request);
106
107 29
        $this->executionContext->setRequest($request);
108 29
    }
109
110
    /**
111
     * @param Query|Field        $query
112
     * @param AbstractObjectType $currentLevelSchema
113
     *
114
     * @return array|bool|mixed
115
     */
116 29
    protected function executeOperation(Query $query, $currentLevelSchema)
117
    {
118 29
        if (!$this->resolveValidator->objectHasField($currentLevelSchema, $query)) {
119 1
            return null;
120
        }
121
122
        /** @var FieldInterface $field */
123 29
        $operationField = $currentLevelSchema->getField($query->getName());
124 29
        $alias          = $query->getAlias() ?: $query->getName();
125
126 29
        if (!$this->resolveValidator->validateArguments($operationField, $query, $this->executionContext->getRequest())) {
127 6
            return null;
128
        }
129
130 26
        return [$alias => $this->processQueryAST($query, $operationField)];
131
    }
132
133
    /**
134
     * @param Query          $query
135
     * @param FieldInterface $field
136
     * @param                $contextValue
137
     *
138
     * @return array|mixed|null
139
     */
140 26
    protected function processQueryAST(Query $query, FieldInterface $field, $contextValue = null)
141
    {
142 26
        if (!$this->resolveValidator->validateArguments($field, $query, $this->executionContext->getRequest())) {
143
            return null;
144
        }
145
146 26
        $resolvedValue = $this->resolveFieldValue($field, $contextValue, $query->getFields(), $this->parseArgumentsValues($field, $query));
147
148 26
        if (!$this->resolveValidator->isValidValueForField($field, $resolvedValue)) {
149 2
            return null;
150
        }
151
152 26
        return $this->collectValueForQueryWithType($query, $field->getType(), $resolvedValue);
153
    }
154
155
    /**
156
     * @param Query|Mutation $query
157
     * @param AbstractType   $fieldType
158
     * @param mixed          $resolvedValue
159
     *
160
     * @return array|mixed
161
     * @throws ResolveException
162
     */
163 26
    protected function collectValueForQueryWithType(Query $query, AbstractType $fieldType, $resolvedValue)
164
    {
165 26
        if (is_null($resolvedValue)) {
166 7
            return null;
167
        }
168
169 24
        $value = [];
170
171 24
        $fieldType = $fieldType->getNullableType();
172
173 24
        if (!$query->hasFields()) {
174 5
            $fieldType = $this->resolveValidator->resolveTypeIfAbstract($fieldType, $resolvedValue);
175
176 5
            if (!TypeService::isLeafType($fieldType->getNamedType())) {
177
                throw new ResolveException(sprintf('You have to specify fields for "%s"', $query->getName()));
178
            }
179 5
            if (TypeService::isScalarType($fieldType)) {
180 5
                return $this->getOutputValue($fieldType, $resolvedValue);
181
            }
182
        }
183
184 21
        if ($fieldType->getKind() == TypeMap::KIND_LIST) {
185 10
            if (!$this->resolveValidator->hasArrayAccess($resolvedValue)) return null;
186
187 10
            $namedType          = $fieldType->getNamedType();
188 10
            $validItemStructure = false;
189
190 10
            foreach ($resolvedValue as $resolvedValueItem) {
0 ignored issues
show
Bug introduced by
The expression $resolvedValue of type object|integer|double|string|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
191 9
                $value[] = [];
192 9
                $index   = count($value) - 1;
193
194 9
                $namedItemType = $this->resolveValidator->resolveTypeIfAbstract($namedType, $resolvedValueItem);
195
196 9
                if (!$validItemStructure) {
197 9
                    if (!$namedItemType->isValidValue($resolvedValueItem)) {
198 1
                        $this->executionContext->addError(new ResolveException(sprintf('Not valid resolve value in %s field', $query->getName())));
199 1
                        $value[$index] = null;
200 1
                        continue;
201
                    }
202 8
                    $validItemStructure = true;
203
                }
204
205 10
                $value[$index] = $this->processQueryFields($query, $namedItemType, $resolvedValueItem, $value[$index]);
206
            }
207
        } else {
208 21
            $value = $this->processQueryFields($query, $fieldType, $resolvedValue, $value);
209
        }
210
211 21
        return $value;
212
    }
213
214
    /**
215
     * @param FieldAst       $fieldAst
216
     * @param FieldInterface $field
217
     *
218
     * @param mixed          $contextValue
219
     *
220
     * @return array|mixed|null
221
     * @throws ResolveException
222
     * @throws \Exception
223
     */
224 20
    protected function processFieldAST(FieldAst $fieldAst, FieldInterface $field, $contextValue)
225
    {
226 20
        $value            = null;
0 ignored issues
show
Unused Code introduced by
$value is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
227 20
        $fieldType        = $field->getType();
228 20
        $preResolvedValue = $this->getPreResolvedValue($contextValue, $fieldAst, $field);
229
230 20
        if ($fieldType->getKind() == TypeMap::KIND_LIST) {
231 1
            $listValue = [];
232 1
            $type      = $fieldType->getNamedType();
233
234 1
            foreach ($preResolvedValue as $resolvedValueItem) {
235 1
                $listValue[] = $this->getOutputValue($type, $resolvedValueItem);
236
            }
237
238 1
            $value = $listValue;
239
        } else {
240 20
            $value = $this->getOutputValue($fieldType, $preResolvedValue);
241
        }
242
243 20
        return $value;
244
    }
245
246 26
    protected function createResolveInfo($field, $fields)
247
    {
248 26
        return new ResolveInfo($field, $fields, $this->executionContext);
249
    }
250
251
    /**
252
     * @param                $contextValue
253
     * @param FieldAst       $fieldAst
254
     * @param FieldInterface $field
255
     *
256
     * @throws \Exception
257
     *
258
     * @return mixed
259
     */
260 20
    protected function getPreResolvedValue($contextValue, FieldAst $fieldAst, FieldInterface $field)
261
    {
262 20
        if ($field->hasArguments() && !$this->resolveValidator->validateArguments($field, $fieldAst, $this->executionContext->getRequest())) {
263
            return null;
264
        }
265
266 20
        return $this->resolveFieldValue($field, $contextValue, [$fieldAst], $fieldAst->getKeyValueArguments());
267
268
    }
269
270 26
    protected function resolveFieldValue(FieldInterface $field, $contextValue, array $fields, array $args)
271
    {
272 26
        return $field->resolve($contextValue, $args, $this->createResolveInfo($field, $fields));
273
    }
274
275
    /**
276
     * @param $field     FieldInterface
277
     * @param $query     Query
278
     *
279
     * @return array
280
     */
281 26
    protected function parseArgumentsValues(FieldInterface $field, Query $query)
282
    {
283 26
        $args = [];
284 26
        foreach ($query->getArguments() as $argument) {
285 15
            if ($configArgument = $field->getArgument($argument->getName())) {
286 15
                $args[$argument->getName()] = $configArgument->getType()->parseValue($argument->getValue()->getValue());
287
            }
288
        }
289
290 26
        return $args;
291
    }
292
293
    /**
294
     * @param $query         Query|FragmentInterface
295
     * @param $queryType     AbstractObjectType|TypeInterface|Field|AbstractType
296
     * @param $resolvedValue mixed
297
     * @param $value         array
298
     *
299
     * @throws \Exception
300
     *
301
     * @return array
302
     */
303 21
    protected function processQueryFields($query, AbstractType $queryType, $resolvedValue, $value)
304
    {
305 21
        $originalType = $queryType;
306 21
        $queryType    = $this->resolveValidator->resolveTypeIfAbstract($queryType, $resolvedValue);
307 21
        $currentType  = $queryType->getNullableType()->getNullableType();
308
309
310 21 View Code Duplication
        if ($currentType->getKind() == TypeMap::KIND_SCALAR) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
311 1
            if (!$query->hasFields()) {
312 1
                return $this->getOutputValue($currentType, $resolvedValue);
313
            } else {
314 1
                $this->executionContext->addError(new ResolveException(sprintf('Fields are not found in query "%s"', $query->getName())));
315
316 1
                return null;
317
            }
318
        }
319
320 21
        foreach ($query->getFields() as $fieldAst) {
321
322 21
            if ($fieldAst instanceof FragmentInterface) {
323
                /** @var TypedFragmentReference $fragment */
324 3
                $fragment = $fieldAst;
325 3
                if ($fieldAst instanceof FragmentReference) {
326
                    /** @var Fragment $fragment */
327 2
                    $fieldAstName = $fieldAst->getName();
328 2
                    $fragment     = $this->executionContext->getRequest()->getFragment($fieldAstName);
329 2
                    $this->resolveValidator->assertValidFragmentForField($fragment, $fieldAst, $originalType);
330 1
                } elseif ($fragment->getTypeName() !== $queryType->getName()) {
331 1
                    continue;
332
                }
333
334 3
                $fragmentValue = $this->processQueryFields($fragment, $queryType, $resolvedValue, $value);
335 3
                $value         = is_array($fragmentValue) ? $fragmentValue : [];
336
            } else {
337 21
                $fieldAstName = $fieldAst->getName();
338 21
                $alias        = $fieldAst->getAlias() ?: $fieldAstName;
339
340 21
                if ($fieldAstName == self::TYPE_NAME_QUERY) {
341 1
                    $value[$alias] = $queryType->getName();
342
                } else {
343 21
                    $field = $currentType->getField($fieldAstName);
344 21
                    if (!$field) {
345 3
                        $this->executionContext->addError(new ResolveException(sprintf('Field "%s" is not found in type "%s"', $fieldAstName, $currentType->getName())));
346
347 3
                        return null;
348
                    }
349 21
                    if ($fieldAst instanceof Query) {
350 11
                        $value[$alias] = $this->processQueryAST($fieldAst, $field, $resolvedValue);
351
                    } elseif ($fieldAst instanceof FieldAst) {
352 20
                        if (!TypeService::isLeafType($field->getType()->getNamedType()->getNullableType())) {
353 1
                            throw new ResolveException(sprintf('You have to specify fields for "%s"', $field->getName()));
354
                        }
355 20
                        $value[$alias] = $this->processFieldAST($fieldAst, $field, $resolvedValue);
356
                    } else {
357 21
                        return $value;
358
                    }
359
                }
360
            }
361
362
        }
363
364 21
        return $value;
365
    }
366
367
    protected function getFieldValidatedValue(FieldInterface $field, $value)
368
    {
369
        return ($this->resolveValidator->isValidValueForField($field, $value)) ? $this->getOutputValue($field->getType(), $value) : null;
370
    }
371
372 23
    protected function getOutputValue(AbstractType $type, $value)
373
    {
374 23
        return in_array($type->getKind(), [TypeMap::KIND_OBJECT, TypeMap::KIND_NON_NULL]) ? $value : $type->serialize($value);
375
    }
376
377 29
    public function getResponseData()
378
    {
379 29
        $result = [];
380
381 29
        if (!empty($this->data)) {
382 26
            $result['data'] = $this->data;
383
        }
384
385 29
        if ($this->executionContext->hasErrors()) {
386 10
            $result['errors'] = $this->executionContext->getErrorsArray();
387
        }
388
389 29
        return $result;
390
    }
391
392
    /**
393
     * You can access ExecutionContext to check errors and inject dependencies
394
     *
395
     * @return ExecutionContext
396
     */
397 9
    public function getExecutionContext()
398
    {
399 9
        return $this->executionContext;
400
    }
401
402
    /**
403
     * Convenience function for attaching a MaxComplexityQueryVisitor($max) to the next processor run
404
     *
405
     * @param int $max
406
     */
407 1
    public function setMaxComplexity($max)
408
    {
409 1
        $this->maxComplexity = $max;
410 1
    }
411
412
    /**
413
     * Apply all of $reducers to this query.  Example reducer operations: checking for maximum query complexity,
414
     * performing look-ahead query planning, etc.
415
     *
416
     * @param AbstractType           $queryType
417
     * @param AbstractType           $mutationType
418
     * @param AbstractQueryVisitor[] $reducers
419
     */
420 29
    protected function reduceQuery($queryType, $mutationType, array $reducers)
421
    {
422 29
        foreach ($reducers as $reducer) {
423 2
            foreach ($this->executionContext->getRequest()->getOperationsInOrder() as $operation) {
424 2
                $this->doVisit($operation, $operation instanceof Mutation ? $mutationType : $queryType, $reducer);
425
            }
426
        }
427 29
    }
428
429
    /**
430
     * Entry point for the `walkQuery` routine.  Execution bounces between here, where the reducer's ->visit() method
431
     * is invoked, and `walkQuery` where we send in the scores from the `visit` call.
432
     *
433
     * @param Query                $query
434
     * @param AbstractType         $currentLevelSchema
435
     * @param AbstractQueryVisitor $reducer
436
     */
437 2
    protected function doVisit(Query $query, $currentLevelSchema, $reducer)
438
    {
439 2
        if (!($currentLevelSchema instanceof AbstractObjectType) || !$currentLevelSchema->hasField($query->getName())) {
440
            return;
441
        }
442
443 2
        if ($operationField = $currentLevelSchema->getField($query->getName())) {
444
445 2
            $coroutine = $this->walkQuery($query, $operationField);
446
447 2
            if ($results = $coroutine->current()) {
448 2
                $queryCost = 0;
449 2
                while ($results) {
450
                    // initial values come from advancing the generator via ->current, subsequent values come from ->send()
451 2
                    list($queryField, $astField, $childCost) = $results;
452
453
                    /**
454
                     * @var Query|FieldAst $queryField
455
                     * @var Field          $astField
456
                     */
457 2
                    $cost = $reducer->visit($queryField->getKeyValueArguments(), $astField->getConfig(), $childCost);
458 2
                    $queryCost += $cost;
459 2
                    $results = $coroutine->send($cost);
460
                }
461
            }
462
        }
463 2
    }
464
465
    /**
466
     * Coroutine to walk the query and schema in DFS manner (see AbstractQueryVisitor docs for more info) and yield a
467
     * tuple of (queryNode, schemaNode, childScore)
468
     *
469
     * childScore costs are accumulated via values sent into the coroutine.
470
     *
471
     * Most of the branching in this function is just to handle the different types in a query: Queries, Unions,
472
     * Fragments (anonymous and named), and Fields.  The core of the function is simple: recurse until we hit the base
473
     * case of a Field and yield that back up to the visitor up in `doVisit`.
474
     *
475
     * @param Query|Field|FragmentInterface $queryNode
476
     * @param FieldInterface                $currentLevelAST
477
     *
478
     * @return \Generator
479
     */
480 2
    protected function walkQuery($queryNode, FieldInterface $currentLevelAST)
481
    {
482 2
        $childrenScore = 0;
483 2
        if (!($queryNode instanceof FieldAst)) {
484 2
            foreach ($queryNode->getFields() as $queryField) {
0 ignored issues
show
Bug introduced by
The method getFields does only exist in Youshido\GraphQL\Field\F...raphQL\Parser\Ast\Query, but not in Youshido\GraphQL\Parser\Ast\FragmentInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
485 2
                if ($queryField instanceof FragmentInterface) {
486 1
                    if ($queryField instanceof FragmentReference) {
487
                        $queryField = $this->executionContext->getRequest()->getFragment($queryField->getName());
488
                    }
489
                    // the next 7 lines are essentially equivalent to `yield from $this->walkQuery(...)` in PHP7.
490
                    // for backwards compatibility this is equivalent.
491
                    // This pattern is repeated multiple times in this function, and unfortunately cannot be extracted or
492
                    // made less verbose.
493 1
                    $gen  = $this->walkQuery($queryField, $currentLevelAST);
0 ignored issues
show
Bug introduced by
It seems like $queryField defined by $this->executionContext-...$queryField->getName()) on line 487 can also be of type null or object<Youshido\GraphQL\Parser\Ast\Fragment>; however, Youshido\GraphQL\Execution\Processor::walkQuery() does only seem to accept object<Youshido\GraphQL\...\Ast\FragmentInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
494 1
                    $next = $gen->current();
495 1
                    while ($next) {
496 1
                        $received = (yield $next);
497 1
                        $childrenScore += (int)$received;
498 1
                        $next = $gen->send($received);
499
                    }
500
                } else {
501 2
                    $fieldType = $currentLevelAST->getType()->getNamedType();
502 2
                    if ($fieldType instanceof AbstractUnionType) {
503 1
                        foreach ($fieldType->getTypes() as $unionFieldType) {
504 1 View Code Duplication
                            if ($fieldAst = $unionFieldType->getField($queryField->getName())) {
0 ignored issues
show
Bug introduced by
The method getField does only exist in Youshido\GraphQL\Type\Object\AbstractObjectType, but not in Youshido\GraphQL\Type\Scalar\AbstractScalarType.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
505 1
                                $gen  = $this->walkQuery($queryField, $fieldAst);
506 1
                                $next = $gen->current();
507 1
                                while ($next) {
508 1
                                    $received = (yield $next);
509 1
                                    $childrenScore += (int)$received;
510 1
                                    $next = $gen->send($received);
511
                                }
512
                            }
513
                        }
514 1 View Code Duplication
                    } elseif ($fieldType instanceof AbstractObjectType && $fieldAst = $fieldType->getField($queryField->getName())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
515 1
                        $gen  = $this->walkQuery($queryField, $fieldAst);
516 1
                        $next = $gen->current();
517 2
                        while ($next) {
518 1
                            $received = (yield $next);
519 1
                            $childrenScore += (int)$received;
520 1
                            $next = $gen->send($received);
521
                        }
522
                    }
523
                }
524
            }
525
        }
526
        // sanity check.  don't yield fragments; they don't contribute to cost
527 2
        if ($queryNode instanceof Query || $queryNode instanceof FieldAst) {
528
            // BASE CASE.  If we're here we're done recursing -
529
            // this node is either a field, or a query that we've finished recursing into.
530 2
            yield [$queryNode, $currentLevelAST, $childrenScore];
531
        }
532 2
    }
533
}
534