Completed
Push — oldjunk ( e9510e )
by Jeroen De
08:00
created

MapsMappingServices::getValidServiceInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Class for interaction with MappingService objects.
5
 *
6
 * @since 0.6.6
7
 *
8
 * @licence GNU GPL v2+
9
 * @author Jeroen De Dauw < [email protected] >
10
 */
11
final class MapsMappingServices {
12
13
	/**
14
	 * Associative array containing service identifiers as keys and the names
15
	 * of service classes as values.
16
	 *
17
	 * @var string[]
18
	 */
19
	private static $registeredServices = [];
20
21
	/**
22
	 * Associative with service identifiers as keys containing instances of
23
	 * the mapping service classes.
24
	 *
25
	 * Note: This list only contains the instances, so is not to be used for
26
	 * looping over all available services, as not all of them are guaranteed
27
	 * to have an instance already, use $registeredServices for this purpose.
28
	 *
29
	 * @var MapsMappingService[]
30
	 */
31
	private static $services = [];
32
33
	/**
34
	 * Registers a service class linked to an identifier.
35
	 */
36
	public static function registerService( string $serviceIdentifier, string $serviceClassName ) {
37
		self::$registeredServices[$serviceIdentifier] = $serviceClassName;
38
	}
39
40
	/**
41
	 * Returns the instance of a service class. This method takes
42
	 * care of creating the instance if this is not done yet.
43
	 *
44
	 * @throws MWException
45
	 */
46
	public static function getServiceInstance( string $serviceIdentifier ): MapsMappingService {
47
		if ( !array_key_exists( $serviceIdentifier, self::$services ) ) {
48
			if ( array_key_exists( $serviceIdentifier, self::$registeredServices ) ) {
49
				$service = new self::$registeredServices[$serviceIdentifier]( $serviceIdentifier );
50
51
				if ( $service instanceof MapsMappingService ) {
52
					self::$services[$serviceIdentifier] = $service;
53
				} else {
54
					throw new MWException(
55
						'The service object linked to service identifier ' . $serviceIdentifier . ' does not implement iMappingService.'
56
					);
57
				}
58
			} else {
59
				throw new MWException(
60
					'There is no service object linked to service identifier ' . $serviceIdentifier . '.'
61
				);
62
			}
63
		}
64
65
		return self::$services[$serviceIdentifier];
66
	}
67
68
}
69