/
QueryCollector.php
83 lines (73 loc) · 2.43 KB
/
QueryCollector.php
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
<?php
namespace SilverStripe\GraphQL\Schema\DataObject\Plugin;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\GraphQL\Schema\Exception\SchemaBuilderException;
use SilverStripe\GraphQL\Schema\Field\Field;
use SilverStripe\GraphQL\Schema\Field\ModelField;
use SilverStripe\GraphQL\Schema\Field\ModelMutation;
use SilverStripe\GraphQL\Schema\Field\ModelQuery;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\GraphQL\Schema\Type\ModelInterfaceType;
use Generator;
use SilverStripe\GraphQL\Schema\Type\ModelType;
class QueryCollector
{
use Injectable;
private Schema $schema;
public function __construct(Schema $schema)
{
$this->schema = $schema;
}
/**
* @throws SchemaBuilderException
*/
public function collectQueries(): array
{
$cached = $this->schema->getState()->get([static::class, 'queries']);
if ($cached) {
return $cached;
}
$queries = [];
foreach ($this->schema->getQueryType()->getFields() as $field) {
if ($field instanceof ModelQuery) {
$queries[] = $field;
}
}
foreach ($this->schema->getMutationType()->getFields() as $field) {
if ($field instanceof ModelMutation) {
$queries[] = $field;
}
}
foreach (array_merge($this->schema->getModels(), $this->schema->getTypes()) as $type) {
foreach ($type->getFields() as $field) {
if ($field instanceof ModelField && $field->getModelType()) {
$queries[] = $field;
}
}
}
foreach ($this->schema->getInterfaces() as $interface) {
if (!$interface instanceof ModelInterfaceType) {
continue;
}
foreach ($interface->getFields() as $field) {
if ($field instanceof ModelField && $field->getModelType()) {
$queries[] = $field;
}
}
}
$this->schema->getState()->set([static::class, 'queries'], $queries);
return $queries;
}
/**
* @throws SchemaBuilderException
*/
public function collectQueriesForType(ModelType $type): Generator
{
/* @var Field $query */
foreach ($this->collectQueries() as $query) {
if ($query->getNamedType() === $type->getName()) {
yield $query;
}
}
}
}