Passed
Push — master ( 3d645a...097498 )
by Tomáš
05:27
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 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\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
	/**
20
	 * {@inheritdoc}
21
	 */
22 6
	public function addField(QueryFieldInterface $queryField): void
23
	{
24 6
		$this->ensureFieldIsNotRegistered($queryField);
25
26 6
		$this->fields[$queryField->getName()] = $queryField;
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): ?QueryFieldInterface
38
	{
39
		return $this->fields[$name] ?? null;
40 2
	}
41
42 2
	/**
43 2
	 * {@inheritdoc}
44 2
	 */
45 1
	public function convertFieldsToArray(?array $allowedQueries = null): array
46
	{
47
		$fields = [];
48 2
		foreach ($this->getFields() as $field) {
49
			if (is_array($allowedQueries) && ! in_array(get_class($field), $allowedQueries, true)) {
50
				continue;
51 2
			}
52
53
			$fields += QueryFieldConverter::toArray($field);
54
		}
55
56
		return $fields;
57 6
	}
58
59 6
	/**
60 1
	 * @throws ExistingQueryFieldException
61 1
	 */
62
	private function ensureFieldIsNotRegistered(QueryFieldInterface $queryField): void
63
	{
64 6
		if (isset($this->fields[$queryField->getName()])) {
65
			throw new ExistingQueryFieldException(
66
				sprintf('Query field with name "%s" is already registered.', $queryField->getName())
67
			);
68
		}
69
	}
70
}
71