|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Portiny\GraphQL\Provider; |
|
6
|
|
|
|
|
7
|
|
|
use Portiny\GraphQL\Contract\Field\QueryFieldInterface; |
|
8
|
|
|
use Portiny\GraphQL\Contract\Provider\QueryFieldsProviderInterface; |
|
9
|
|
|
use Portiny\GraphQL\Converter\QueryFieldConverter; |
|
10
|
|
|
use Portiny\GraphQL\Exception\Provider\ExistingQueryFieldException; |
|
11
|
|
|
|
|
12
|
|
|
final class QueryFieldsProvider implements QueryFieldsProviderInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var QueryFieldInterface[] |
|
16
|
|
|
*/ |
|
17
|
|
|
private $fields = []; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(iterable $queryFields = []) |
|
20
|
|
|
{ |
|
21
|
|
|
foreach ($queryFields as $queryField) { |
|
22
|
6 |
|
$this->addField($queryField); |
|
23
|
|
|
} |
|
24
|
6 |
|
} |
|
25
|
|
|
|
|
26
|
6 |
|
/** |
|
27
|
6 |
|
* {@inheritdoc} |
|
28
|
|
|
*/ |
|
29
|
|
|
public function addField(QueryFieldInterface $queryField): void |
|
30
|
|
|
{ |
|
31
|
|
|
$this->ensureFieldIsNotRegistered($queryField); |
|
32
|
5 |
|
|
|
33
|
|
|
$this->fields[$queryField->getName()] = $queryField; |
|
34
|
5 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* {@inheritdoc} |
|
38
|
|
|
*/ |
|
39
|
|
|
public function getFields(): array |
|
40
|
|
|
{ |
|
41
|
|
|
return $this->fields; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function getField(string $name): ?QueryFieldInterface |
|
45
|
2 |
|
{ |
|
46
|
|
|
return $this->fields[$name] ?? null; |
|
47
|
2 |
|
} |
|
48
|
2 |
|
|
|
49
|
2 |
|
/** |
|
50
|
1 |
|
* {@inheritdoc} |
|
51
|
|
|
*/ |
|
52
|
|
|
public function convertFieldsToArray(?array $allowedQueries = null): array |
|
53
|
2 |
|
{ |
|
54
|
|
|
$fields = []; |
|
55
|
|
|
foreach ($this->getFields() as $field) { |
|
56
|
2 |
|
if (is_array($allowedQueries) && ! in_array(get_class($field), $allowedQueries, true)) { |
|
57
|
|
|
continue; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
$fields += QueryFieldConverter::toArray($field); |
|
61
|
|
|
} |
|
62
|
6 |
|
|
|
63
|
|
|
return $fields; |
|
64
|
6 |
|
} |
|
65
|
1 |
|
|
|
66
|
1 |
|
/** |
|
67
|
|
|
* @throws ExistingQueryFieldException |
|
68
|
|
|
*/ |
|
69
|
6 |
|
private function ensureFieldIsNotRegistered(QueryFieldInterface $queryField): void |
|
70
|
|
|
{ |
|
71
|
|
|
if (isset($this->fields[$queryField->getName()])) { |
|
72
|
|
|
throw new ExistingQueryFieldException( |
|
73
|
|
|
sprintf('Query field with name "%s" is already registered.', $queryField->getName()) |
|
74
|
|
|
); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|