Completed
Push — master ( 4d0076...81538e )
by Jeroen De
26s queued 11s
created

MappingServices::getDefaultService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace Maps;
6
7
/**
8
 * @licence GNU GPL v2+
9
 * @author Jeroen De Dauw < [email protected] >
10
 */
11
final class MappingServices {
12
13
	/**
14
	 * @var MappingService[]
15
	 */
16
	private $nameToServiceMap = [];
17
18
	/**
19
	 * @var string Name of the default service, which is used as fallback
20
	 */
21
	private $defaultService;
22
23
	/**
24
	 * @param string[] $availableServices
25
	 * @param string $defaultService
26
	 * @param MappingService ...$services
27
	 * @throws \InvalidArgumentException
28
	 */
29 27
	public function __construct( array $availableServices, string $defaultService, MappingService ...$services ) {
30 27
		$this->defaultService = $defaultService;
31
32 27
		foreach ( $services as $service ) {
33 27
			if ( in_array( $service->getName(), $availableServices ) ) {
34 27
				$this->nameToServiceMap[$service->getName()] = $service;
35
36 27
				foreach ( $service->getAliases() as $alias ) {
37 27
					$this->nameToServiceMap[$alias] = $service;
38
				}
39
			}
40
		}
41
42 27
		if ( !$this->nameIsKnown( $defaultService ) ) {
43
			throw new \InvalidArgumentException( 'The default mapping service needs to be available' );
44
		}
45 27
	}
46
47
	/**
48
	 * @param string $name Name or alias of a service
49
	 * @return bool
50
	 */
51 27
	public function nameIsKnown( string $name ): bool {
52 27
		return array_key_exists( $name, $this->nameToServiceMap );
53
	}
54
55
	/**
56
	 * @param string $name Name or alias of a service
57
	 * @return MappingService
58
	 * @throws \OutOfBoundsException
59
	 */
60
	public function getService( string $name ): MappingService {
61
		if ( !$this->nameIsKnown( $name ) ) {
62
			throw new \OutOfBoundsException();
63
		}
64
65
		return $this->nameToServiceMap[$name];
66
	}
67
68
	/**
69
	 * @param string $name Name or alias of a service
70
	 * @return MappingService
71
	 */
72 27
	public function getServiceOrDefault( string $name ): MappingService {
73 27
		if ( $this->nameIsKnown( $name ) ) {
74 9
			return $this->nameToServiceMap[$name];
75
		}
76
77 18
		return $this->getDefaultService();
78
	}
79
80 27
	public function getAllNames(): array {
81 27
		return array_keys( $this->nameToServiceMap );
82
	}
83
84 18
	public function getDefaultService(): MappingService {
85 18
		return $this->nameToServiceMap[$this->defaultService];
86
	}
87
88
}
89