1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Framework\GraphQl\Query;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\NodeKind;
/**
* This class holds a list of all queried fields and is used to enable performance optimization for schema loading.
*/
class Fields
{
/**
* @var string[]
*/
private $fieldsUsedInQuery = [];
/**
* Set Query for extracting list of fields.
*
* @param string $query
* @param array|null $variables
*
* @return void
*/
public function setQuery($query, array $variables = null)
{
$queryFields = [];
try {
$queryAst = \GraphQL\Language\Parser::parse(new \GraphQL\Language\Source($query ?: '', 'GraphQL'));
\GraphQL\Language\Visitor::visit(
$queryAst,
[
'leave' => [
NodeKind::NAME => function (Node $node) use (&$queryFields) {
$queryFields[$node->value] = $node->value;
}
]
]
);
if (isset($variables)) {
$queryFields = array_merge($queryFields, $this->extractVariables($variables));
}
} catch (\Exception $e) {
// If a syntax error is encountered do not collect fields
}
if (isset($queryFields['IntrospectionQuery'])) {
// It must be possible to query any fields during introspection query
$queryFields = [];
}
$this->fieldsUsedInQuery = $queryFields;
}
/**
* Get list of fields used in GraphQL query.
*
* This method is stateful and relies on the query being set with setQuery.
*
* @return string[]
*/
public function getFieldsUsedInQuery()
{
return $this->fieldsUsedInQuery;
}
/**
* Extract and return list of all used fields in GraphQL query's variables
*
* @param array $variables
*
* @return string[]
*/
private function extractVariables(array $variables): array
{
$fields = [];
foreach ($variables as $key => $value) {
if (is_array($value)) {
$fields = array_merge($fields, $this->extractVariables($value));
}
$fields[$key] = $key;
}
return $fields;
}
}