Completed
Push — master ( 0ade26...46306f )
by Alexandr
04:16
created

Processor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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