Completed
Push — master ( ea305a...d84c25 )
by Alexandr
03:17
created

Processor::setMaxComplexity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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