Passed
Push — master ( 193c16...705327 )
by Tomáš
11:03
created

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