7
7
8
8
namespace Magento \CatalogGraphQl \Model \Category ;
9
9
10
+ use GraphQL \Language \AST \Node ;
10
11
use GraphQL \Language \AST \FieldNode ;
11
12
use GraphQL \Language \AST \InlineFragmentNode ;
12
13
use GraphQL \Language \AST \NodeKind ;
@@ -26,22 +27,35 @@ class DepthCalculator
26
27
*/
27
28
public function calculate (ResolveInfo $ resolveInfo , FieldNode $ fieldNode ) : int
28
29
{
29
- $ selections = $ fieldNode ->selectionSet ->selections ?? [];
30
+ return $ this ->calculateRecursive ($ resolveInfo , $ fieldNode );
31
+ }
32
+
33
+ /**
34
+ * Calculate recursive the total depth of a category tree inside a GraphQL request
35
+ *
36
+ * @param ResolveInfo $resolveInfo
37
+ * @param Node $node
38
+ * @return int
39
+ */
40
+ private function calculateRecursive (ResolveInfo $ resolveInfo , Node $ node ) : int
41
+ {
42
+ if ($ node ->kind === NodeKind::FRAGMENT_SPREAD ) {
43
+ $ selections = isset ($ resolveInfo ->fragments [$ node ->name ->value ]) ?
44
+ $ resolveInfo ->fragments [$ node ->name ->value ]->selectionSet ->selections : [];
45
+ } else {
46
+ $ selections = $ node ->selectionSet ->selections ?? [];
47
+ }
30
48
$ depth = count ($ selections ) ? 1 : 0 ;
31
49
$ childrenDepth = [0 ];
32
- foreach ($ selections as $ node ) {
33
- if (isset ($ node ->alias ) && null !== $ node ->alias ) {
50
+ foreach ($ selections as $ subNode ) {
51
+ if (isset ($ subNode ->alias ) && null !== $ subNode ->alias ) {
34
52
continue ;
35
53
}
36
54
37
- if ($ node ->kind === NodeKind::INLINE_FRAGMENT ) {
38
- $ childrenDepth [] = $ this ->addInlineFragmentDepth ($ resolveInfo , $ node );
39
- } elseif ($ node ->kind === NodeKind::FRAGMENT_SPREAD && isset ($ resolveInfo ->fragments [$ node ->name ->value ])) {
40
- foreach ($ resolveInfo ->fragments [$ node ->name ->value ]->selectionSet ->selections as $ spreadNode ) {
41
- $ childrenDepth [] = $ this ->calculate ($ resolveInfo , $ spreadNode );
42
- }
55
+ if ($ subNode ->kind === NodeKind::INLINE_FRAGMENT ) {
56
+ $ childrenDepth [] = $ this ->addInlineFragmentDepth ($ resolveInfo , $ subNode );
43
57
} else {
44
- $ childrenDepth [] = $ this ->calculate ($ resolveInfo , $ node );
58
+ $ childrenDepth [] = $ this ->calculateRecursive ($ resolveInfo , $ subNode );
45
59
}
46
60
}
47
61
0 commit comments