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