Completed
Push — master ( c162bb...a7a918 )
by Portey
03:50
created

Processor::processPayload()   B

Complexity

Conditions 6
Paths 26

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 29
ccs 14
cts 14
cp 1
rs 8.439
c 1
b 1
f 0
cc 6
eloc 15
nc 26
nop 3
crap 6
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\Context\ExecutionContext;
13
use Youshido\GraphQL\Execution\Visitor\AbstractQueryVisitor;
14
use Youshido\GraphQL\Execution\Visitor\MaxComplexityQueryVisitor;
15
use Youshido\GraphQL\Field\AbstractField;
16
use Youshido\GraphQL\Field\Field;
17
use Youshido\GraphQL\Introspection\Field\SchemaField;
18
use Youshido\GraphQL\Introspection\Field\TypeDefinitionField;
19
use Youshido\GraphQL\Parser\Ast\Field as FieldAst;
20
use Youshido\GraphQL\Parser\Ast\Fragment;
21
use Youshido\GraphQL\Parser\Ast\FragmentInterface;
22
use Youshido\GraphQL\Parser\Ast\FragmentReference;
23
use Youshido\GraphQL\Parser\Ast\Mutation;
24
use Youshido\GraphQL\Parser\Ast\Query;
25
use Youshido\GraphQL\Parser\Ast\TypedFragmentReference;
26
use Youshido\GraphQL\Parser\Parser;
27
use Youshido\GraphQL\Schema\AbstractSchema;
28
use Youshido\GraphQL\Type\AbstractType;
29
use Youshido\GraphQL\Type\Object\AbstractObjectType;
30
use Youshido\GraphQL\Type\TypeInterface;
31
use Youshido\GraphQL\Type\TypeMap;
32
use Youshido\GraphQL\Type\TypeService;
33
use Youshido\GraphQL\Type\Union\AbstractUnionType;
34
use Youshido\GraphQL\Validator\Exception\ResolveException;
35
use Youshido\GraphQL\Validator\ResolveValidator\ResolveValidator;
36
use Youshido\GraphQL\Validator\ResolveValidator\ResolveValidatorInterface;
37
use Youshido\GraphQL\Validator\SchemaValidator\SchemaValidator;
38
39
class Processor
40
{
41
42
    const TYPE_NAME_QUERY = '__typename';
43
44
    /** @var  array */
45
    protected $data;
46
47
    /** @var ResolveValidatorInterface */
48
    protected $resolveValidator;
49
50
    /** @var ExecutionContext */
51
    protected $executionContext;
52
53
    /** @var int */
54
    protected $maxComplexity;
55
56 29
    public function __construct(AbstractSchema $schema)
57
    {
58 29
        $this->executionContext = new ExecutionContext();
59
60
        try {
61 29
            (new SchemaValidator())->validate($schema);
62 1
        } catch (\Exception $e) {
63 1
            $this->executionContext->addError($e);
64
        };
65
66 29
        $this->introduceIntrospectionFields($schema);
67 29
        $this->executionContext->setSchema($schema);
68
69 29
        $this->resolveValidator = new ResolveValidator($this->executionContext);
70 29
    }
71
72 27
    public function processPayload($payload, $variables = [], $reducers = [])
73
    {
74
75 27
        $this->data = [];
76
77
        try {
78 27
            $this->parseAndCreateRequest($payload, $variables);
79
80 27
            $queryType    = $this->executionContext->getSchema()->getQueryType();
81 27
            $mutationType = $this->executionContext->getSchema()->getMutationType();
82
83 27
            if ($this->maxComplexity) {
84 1
                $reducers[] = new MaxComplexityQueryVisitor($this->maxComplexity);
85
            }
86
87 27
            $this->reduceQuery($queryType, $mutationType, $reducers);
88
89 27
            foreach ($this->executionContext->getRequest()->getOperationsInOrder() as $operation) {
90 27
                if ($operationResult = $this->executeOperation($operation, $operation instanceof Mutation ? $mutationType : $queryType)) {
91 27
                    $this->data = array_merge($this->data, $operationResult);
92
                };
93
            }
94
95 4
        } catch (\Exception $e) {
96 4
            $this->executionContext->addError($e);
97
        }
98
99 27
        return $this;
100
    }
101
102 27
    protected function parseAndCreateRequest($payload, $variables = [])
103
    {
104 27
        if (empty($payload)) {
105 1
            throw new \Exception('Must provide an operation.');
106
        }
107 27
        $parser = new Parser();
108
109 27
        $data = $parser->parse($payload);
110 27
        $this->executionContext->setRequest(new Request($data, $variables));
111 27
    }
112
113
    /**
114
     * @param Query|Field        $query
115
     * @param AbstractObjectType $currentLevelSchema
116
     * @return array|bool|mixed
117
     */
118 27
    protected function executeOperation(Query $query, $currentLevelSchema)
119
    {
120 27
        if (!$this->resolveValidator->objectHasField($currentLevelSchema, $query)) {
121 1
            return null;
122
        }
123
124
        /** @var AbstractField $field */
125 27
        $operationField = $currentLevelSchema->getField($query->getName());
126 27
        $alias          = $query->getAlias() ?: $query->getName();
127
128 27
        if (!$this->resolveValidator->validateArguments($operationField, $query, $this->executionContext->getRequest())) {
129 6
            return null;
130
        }
131
132 24
        return [$alias => $this->processQueryAST($query, $operationField)];
133
    }
134
135
    /**
136
     * @param Query         $query
137
     * @param AbstractField $field
138
     * @param               $contextValue
139
     * @return array|mixed|null
140
     */
141 24
    protected function processQueryAST(Query $query, AbstractField $field, $contextValue = null)
142
    {
143 24
        if (!$this->resolveValidator->validateArguments($field, $query, $this->executionContext->getRequest())) {
144
            return null;
145
        }
146
147 24
        $resolvedValue = $this->resolveFieldValue($field, $contextValue, $query->getFields(), $this->parseArgumentsValues($field, $query));
148
149 24
        if (!$this->resolveValidator->isValidValueForField($field, $resolvedValue)) {
150 2
            return null;
151
        }
152
153 24
        return $this->collectValueForQueryWithType($query, $field->getType(), $resolvedValue);
154
    }
155
156
    /**
157
     * @param Query|Mutation $query
158
     * @param AbstractType   $fieldType
159
     * @param mixed          $resolvedValue
160
     * @return array|mixed
161
     * @throws ResolveException
162
     */
163 24
    protected function collectValueForQueryWithType(Query $query, AbstractType $fieldType, $resolvedValue)
164
    {
165 24
        if (is_null($resolvedValue)) {
166 7
            return null;
167
        }
168
169 22
        $value = [];
170
171 22
        if (!$query->hasFields()) {
172 5
            $fieldType = $this->resolveValidator->resolveTypeIfAbstract($fieldType, $resolvedValue);
173
174 5
            if (TypeService::isObjectType($fieldType->getNamedType())) {
175 1
                throw new ResolveException(sprintf('You have to specify fields for "%s"', $query->getName()));
176
            }
177 4
            if (TypeService::isScalarType($fieldType)) {
178 4
                return $this->getOutputValue($fieldType, $resolvedValue);
179
            }
180
        }
181
182 20
        if ($fieldType->getKind() == TypeMap::KIND_LIST) {
183 9
            if (!$this->resolveValidator->hasArrayAccess($resolvedValue)) return null;
184
185 9
            $namedType          = $fieldType->getNamedType();
186 9
            $isAbstract         = TypeService::isAbstractType($namedType);
187 9
            $validItemStructure = false;
188
189 9
            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...
190 8
                $value[] = [];
191 8
                $index   = count($value) - 1;
192
193 8
                if ($isAbstract) {
194 2
                    $namedType = $this->resolveValidator->resolveAbstractType($fieldType->getNamedType(), $resolvedValueItem);
195
                }
196
197 8
                if (!$validItemStructure) {
198 8
                    if (!$namedType->isValidValue($resolvedValueItem)) {
199 1
                        $this->executionContext->addError(new ResolveException(sprintf('Not valid resolve value in %s field', $query->getName())));
200 1
                        $value[$index] = null;
201 1
                        continue;
202
                    }
203 7
                    $validItemStructure = true;
204
                }
205
206 9
                $value[$index] = $this->processQueryFields($query, $namedType, $resolvedValueItem, $value[$index]);
207
            }
208
        } else {
209 20
            $value = $this->processQueryFields($query, $fieldType, $resolvedValue, $value);
210
        }
211
212 20
        return $value;
213
    }
214
215
    /**
216
     * @param FieldAst      $fieldAst
217
     * @param AbstractField $field
218
     *
219
     * @param mixed         $contextValue
220
     * @return array|mixed|null
221
     * @throws ResolveException
222
     * @throws \Exception
223
     */
224 19
    protected function processFieldAST(FieldAst $fieldAst, AbstractField $field, $contextValue)
225
    {
226 19
        $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 19
        $fieldType        = $field->getType();
228 19
        $preResolvedValue = $this->getPreResolvedValue($contextValue, $fieldAst, $field);
229
230 19
        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 19
            $value = $this->getOutputValue($fieldType, $preResolvedValue);
241
        }
242
243 19
        return $value;
244
    }
245
246 24
    protected function createResolveInfo($field, $fields)
247
    {
248 24
        return new ResolveInfo($field, $fields, $this->executionContext);
249
    }
250
251
    /**
252
     * @param               $contextValue
253
     * @param FieldAst      $fieldAst
254
     * @param AbstractField $field
255
     *
256
     * @throws \Exception
257
     *
258
     * @return mixed
259
     */
260 19
    protected function getPreResolvedValue($contextValue, FieldAst $fieldAst, AbstractField $field)
261
    {
262 19
        if ($field->hasArguments() && !$this->resolveValidator->validateArguments($field, $fieldAst, $this->executionContext->getRequest())) {
263
            throw new \Exception(sprintf('Not valid arguments for the field "%s"', $fieldAst->getName()));
264
265
        }
266
267 19
        return $this->resolveFieldValue($field, $contextValue, [$fieldAst], $fieldAst->getKeyValueArguments());
268
269
    }
270
271 24
    protected function resolveFieldValue(AbstractField $field, $contextValue, array $fields, array $args)
272
    {
273 24
        return $field->resolve($contextValue, $args, $this->createResolveInfo($field, $fields));
274
    }
275
276
    /**
277
     * @param $field     AbstractField
278
     * @param $query     Query
279
     *
280
     * @return array
281
     */
282 24
    protected function parseArgumentsValues(AbstractField $field, Query $query)
283
    {
284 24
        $args = [];
285 24
        foreach ($query->getArguments() as $argument) {
286 15
            if ($configArgument = $field->getConfig()->getArgument($argument->getName())) {
287 15
                $args[$argument->getName()] = $configArgument->getType()->parseValue($argument->getValue()->getValue());
288
            }
289
        }
290
291 24
        return $args;
292
    }
293
294
    /**
295
     * @param $query         Query|FragmentInterface
296
     * @param $queryType     AbstractObjectType|TypeInterface|Field|AbstractType
297
     * @param $resolvedValue mixed
298
     * @param $value         array
299
     *
300
     * @throws \Exception
301
     *
302
     * @return array
303
     */
304 20
    protected function processQueryFields($query, AbstractType $queryType, $resolvedValue, $value)
305
    {
306 20
        $originalType = $queryType;
307 20
        $queryType    = $this->resolveValidator->resolveTypeIfAbstract($queryType, $resolvedValue);
308 20
        $currentType  = $queryType->getNullableType();
309
310
311 20 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...
312 1
            if (!$query->hasFields()) {
313 1
                return $this->getOutputValue($currentType, $resolvedValue);
314
            } else {
315 1
                $this->executionContext->addError(new ResolveException(sprintf('Fields are not found in query "%s"', $query->getName())));
316
317 1
                return null;
318
            }
319
        }
320
321 20
        foreach ($query->getFields() as $fieldAst) {
322
323 20
            if ($fieldAst instanceof FragmentInterface) {
324
                /** @var TypedFragmentReference $fragment */
325 3
                $fragment = $fieldAst;
326 3
                if ($fieldAst instanceof FragmentReference) {
327
                    /** @var Fragment $fragment */
328 2
                    $fieldAstName = $fieldAst->getName();
329 2
                    $fragment     = $this->executionContext->getRequest()->getFragment($fieldAstName);
330 2
                    $this->resolveValidator->assertValidFragmentForField($fragment, $fieldAst, $originalType);
331 1
                } elseif ($fragment->getTypeName() !== $queryType->getName()) {
332 1
                    continue;
333
                }
334
335 3
                $fragmentValue = $this->processQueryFields($fragment, $queryType, $resolvedValue, $value);
336 3
                $value         = is_array($fragmentValue) ? $fragmentValue : [];
337
            } else {
338 20
                $fieldAstName = $fieldAst->getName();
339 20
                $alias        = $fieldAst->getAlias() ?: $fieldAstName;
340
341 20
                if ($fieldAstName == self::TYPE_NAME_QUERY) {
342 1
                    $value[$alias] = $queryType->getName();
343
                } else {
344 20
                    $field = $currentType->getField($fieldAstName);
345 20
                    if (!$field) {
346 3
                        $this->executionContext->addError(new ResolveException(sprintf('Field "%s" is not found in type "%s"', $fieldAstName, $currentType->getName())));
347
348 3
                        return null;
349
                    }
350 20
                    if ($fieldAst instanceof Query) {
351 10
                        $value[$alias] = $this->processQueryAST($fieldAst, $field, $resolvedValue);
352
                    } elseif ($fieldAst instanceof FieldAst) {
353 19
                        $value[$alias] = $this->processFieldAST($fieldAst, $field, $resolvedValue);
354
                    } else {
355 20
                        return $value;
356
                    }
357
                }
358
            }
359
360
        }
361
362 20
        return $value;
363
    }
364
365
    protected function getFieldValidatedValue(AbstractField $field, $value)
366
    {
367
        return ($this->resolveValidator->isValidValueForField($field, $value)) ? $this->getOutputValue($field->getType(), $value) : null;
368
    }
369
370 21
    protected function getOutputValue(AbstractType $type, $value)
371
    {
372 21
        return in_array($type->getKind(), [TypeMap::KIND_OBJECT, TypeMap::KIND_NON_NULL]) ? $value : $type->serialize($value);
373
    }
374
375 29
    protected function introduceIntrospectionFields(AbstractSchema $schema)
376
    {
377 29
        $schemaField = new SchemaField();
378 29
        $schema->addQueryField($schemaField);
379 29
        $schema->addQueryField(new TypeDefinitionField());
380 29
    }
381
382 27
    public function getResponseData()
383
    {
384 27
        $result = [];
385
386 27
        if (!empty($this->data)) {
387 24
            $result['data'] = $this->data;
388
        }
389
390 27
        if ($this->executionContext->hasErrors()) {
391 10
            $result['errors'] = $this->executionContext->getErrorsArray();
392
        }
393
394 27
        return $result;
395
    }
396
397
    /**
398
     * You can access ExecutionContext to check errors and inject dependencies
399
     *
400
     * @return ExecutionContext
401
     */
402 8
    public function getExecutionContext()
403
    {
404 8
        return $this->executionContext;
405
    }
406
407
    /**
408
     * Convenience function for attaching a MaxComplexityQueryVisitor($max) to the next processor run
409
     *
410
     * @param int $max
411
     */
412 1
    public function setMaxComplexity($max)
413
    {
414 1
        $this->maxComplexity = $max;
415 1
    }
416
417
    /**
418
     * Apply all of $reducers to this query.  Example reducer operations: checking for maximum query complexity,
419
     * performing look-ahead query planning, etc.
420
     *
421
     * @param AbstractType           $queryType
422
     * @param AbstractType           $mutationType
423
     * @param AbstractQueryVisitor[] $reducers
424
     */
425 27
    protected function reduceQuery($queryType, $mutationType, array $reducers)
426
    {
427 27
        foreach ($reducers as $reducer) {
428 2
            foreach ($this->executionContext->getRequest()->getOperationsInOrder() as $operation) {
429 2
                $this->doVisit($operation, $operation instanceof Mutation ? $mutationType : $queryType, $reducer);
430
            }
431
        }
432 27
    }
433
434
    /**
435
     * Entry point for the `walkQuery` routine.  Execution bounces between here, where the reducer's ->visit() method
436
     * is invoked, and `walkQuery` where we send in the scores from the `visit` call.
437
     *
438
     * @param Query                $query
439
     * @param AbstractType         $currentLevelSchema
440
     * @param AbstractQueryVisitor $reducer
441
     */
442 2
    protected function doVisit(Query $query, $currentLevelSchema, $reducer)
443
    {
444 2
        if (!($currentLevelSchema instanceof AbstractObjectType) || !$currentLevelSchema->hasField($query->getName())) {
445
            return;
446
        }
447
448 2
        if ($operationField = $currentLevelSchema->getField($query->getName())) {
449
450 2
            $coroutine = $this->walkQuery($query, $operationField);
451
452 2
            if ($results = $coroutine->current()) {
453 2
                $queryCost = 0;
454 2
                while ($results) {
455
                    // initial values come from advancing the generator via ->current, subsequent values come from ->send()
456 2
                    list($queryField, $astField, $childCost) = $results;
457
458
                    /**
459
                     * @var Query|FieldAst $queryField
460
                     * @var Field          $astField
461
                     */
462 2
                    $cost = $reducer->visit($queryField->getKeyValueArguments(), $astField->getConfig(), $childCost);
463 2
                    $queryCost += $cost;
464 2
                    $results = $coroutine->send($cost);
465
                }
466
            }
467
        }
468 2
    }
469
470
    /**
471
     * Coroutine to walk the query and schema in DFS manner (see AbstractQueryVisitor docs for more info) and yield a
472
     * tuple of (queryNode, schemaNode, childScore)
473
     *
474
     * childScore costs are accumulated via values sent into the coroutine.
475
     *
476
     * Most of the branching in this function is just to handle the different types in a query: Queries, Unions,
477
     * Fragments (anonymous and named), and Fields.  The core of the function is simple: recurse until we hit the base
478
     * case of a Field and yield that back up to the visitor up in `doVisit`.
479
     *
480
     * @param Query|Field|FragmentInterface $queryNode
481
     * @param AbstractField                 $currentLevelAST
482
     *
483
     * @return \Generator
484
     */
485 2
    protected function walkQuery($queryNode, AbstractField $currentLevelAST)
486
    {
487 2
        $childrenScore = 0;
488 2
        if (!($queryNode instanceof FieldAst)) {
489 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...
490 2
                if ($queryField instanceof FragmentInterface) {
491 1
                    if ($queryField instanceof FragmentReference) {
492
                        $queryField = $this->executionContext->getRequest()->getFragment($queryField->getName());
493
                    }
494
                    // the next 7 lines are essentially equivalent to `yield from $this->walkQuery(...)` in PHP7.
495
                    // for backwards compatibility this is equivalent.
496
                    // This pattern is repeated multiple times in this function, and unfortunately cannot be extracted or
497
                    // made less verbose.
498 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 492 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...
499 1
                    $next = $gen->current();
500 1
                    while ($next) {
501 1
                        $received = (yield $next);
502 1
                        $childrenScore += (int)$received;
503 1
                        $next = $gen->send($received);
504
                    }
505
                } else {
506 2
                    $fieldType = $currentLevelAST->getType()->getNamedType();
507 2
                    if ($fieldType instanceof AbstractUnionType) {
508 1
                        foreach ($fieldType->getTypes() as $unionFieldType) {
509 1 View Code Duplication
                            if ($fieldAst = $unionFieldType->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...
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...
510 1
                                $gen  = $this->walkQuery($queryField, $fieldAst);
511 1
                                $next = $gen->current();
512 1
                                while ($next) {
513 1
                                    $received = (yield $next);
514 1
                                    $childrenScore += (int)$received;
515 1
                                    $next = $gen->send($received);
516
                                }
517
                            }
518
                        }
519 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...
520 1
                        $gen  = $this->walkQuery($queryField, $fieldAst);
521 1
                        $next = $gen->current();
522 2
                        while ($next) {
523 1
                            $received = (yield $next);
524 1
                            $childrenScore += (int)$received;
525 1
                            $next = $gen->send($received);
526
                        }
527
                    }
528
                }
529
            }
530
        }
531
        // sanity check.  don't yield fragments; they don't contribute to cost
532 2
        if ($queryNode instanceof Query || $queryNode instanceof FieldAst) {
533
            // BASE CASE.  If we're here we're done recursing -
534
            // this node is either a field, or a query that we've finished recursing into.
535 2
            yield [$queryNode, $currentLevelAST, $childrenScore];
536
        }
537 2
    }
538
}
539