Passed
Push — master ( b4eada...a03493 )
by Tomáš
04:06
created

MutationFieldsProvider   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 86.96%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 68
ccs 20
cts 23
cp 0.8696
rs 10
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A getField() 0 3 1
A addField() 0 5 1
A ensureFieldIsNotRegistered() 0 5 2
A getFields() 0 3 1
A convertFieldsToArray() 0 12 4
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