Passed
Push — master ( 3d645a...097498 )
by Tomáš
05:27
created

MutationFieldsProvider::getField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
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
	/**
20
	 * {@inheritdoc}
21
	 */
22 6
	public function addField(MutationFieldInterface $mutationField): void
23
	{
24 6
		$this->ensureFieldIsNotRegistered($mutationField);
25
26 6
		$this->fields[$mutationField->getName()] = $mutationField;
27 6
	}
28
29
	/**
30
	 * {@inheritdoc}
31
	 */
32 5
	public function getFields(): array
33
	{
34 5
		return $this->fields;
35
	}
36
37
	public function getField(string $name): ?MutationFieldInterface
38
	{
39
		return $this->fields[$name] ?? null;
40 2
	}
41
42 2
	/**
43 2
	 * {@inheritdoc}
44 2
	 */
45 1
	public function convertFieldsToArray(?array $allowedMutations = null): array
46
	{
47
		$fields = [];
48 2
		foreach ($this->getFields() as $field) {
49
			if (is_array($allowedMutations) && ! in_array(get_class($field), $allowedMutations, true)) {
50
				continue;
51 2
			}
52
53
			$fields += MutationFieldConverter::toArray($field);
54
		}
55
56
		return $fields;
57 6
	}
58
59 6
	/**
60 1
	 * @throws ExistingMutationFieldException
61 1
	 */
62
	private function ensureFieldIsNotRegistered(MutationFieldInterface $mutationField): void
63
	{
64 6
		if (isset($this->fields[$mutationField->getName()])) {
65
			throw new ExistingMutationFieldException(
66
				sprintf('Mutation field with name "%s" is already registered.', $mutationField->getName())
67
			);
68
		}
69
	}
70
}
71