Completed
Push — master ( a7a34c...1e3be1 )
by Jeroen De
03:21
created

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