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