Completed
Pull Request — master (#36)
by Sebastian
09:10 queued 05:33
created

Processor::collectValue()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

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