Passed
Push — master ( 617535...431355 )
by Tomáš
05:19
created

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