77
88namespace Magento \CatalogGraphQl \Model \Category ;
99
10+ use GraphQL \Language \AST \Node ;
1011use GraphQL \Language \AST \FieldNode ;
1112use GraphQL \Language \AST \InlineFragmentNode ;
1213use GraphQL \Language \AST \NodeKind ;
@@ -26,22 +27,35 @@ class DepthCalculator
2627 */
2728 public function calculate (ResolveInfo $ resolveInfo , FieldNode $ fieldNode ) : int
2829 {
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+ }
3048 $ depth = count ($ selections ) ? 1 : 0 ;
3149 $ 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 ) {
3452 continue ;
3553 }
3654
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 );
4357 } else {
44- $ childrenDepth [] = $ this ->calculate ($ resolveInfo , $ node );
58+ $ childrenDepth [] = $ this ->calculateRecursive ($ resolveInfo , $ subNode );
4559 }
4660 }
4761
0 commit comments