Passed
Pull Request — master (#2028)
by Gabriel
203:46 queued 138:41
created

EnvironmentDependentConfigReaderFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 39
c 1
b 0
f 0
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getConfigReader() 0 4 1
A __construct() 0 2 1
A getConfigurationPathsForEnvironment() 0 8 1
A removeNonexistentOptionalPaths() 0 5 2
A checkIfPathsExist() 0 8 2
1
<?php
2
declare( strict_types=1 );
3
4
namespace WMDE\Fundraising\Frontend\Factories;
5
6
use FileFetcher\SimpleFileFetcher;
7
use WMDE\Fundraising\Frontend\Infrastructure\ConfigReader;
8
9
class EnvironmentDependentConfigReaderFactory {
10
	private string $environmentName;
11
12
	public function __construct( string $environmentName ) {
13
		$this->environmentName = $environmentName;
14
	}
15
16
	public function getConfigReader(): ConfigReader {
17
		return new ConfigReader(
18
			new SimpleFileFetcher(),
19
			...$this->getConfigurationPathsForEnvironment( __DIR__ . '/../../app/config' )
20
		);
21
	}
22
23
	public function getConfigurationPathsForEnvironment( string $configPath ): array {
24
		$paths = self::removeNonexistentOptionalPaths( ...[
25
			$configPath . '/config.dist.json',
26
			$configPath . '/config.' . $this->environmentName . '.json',
27
			$configPath . '/config.' . $this->environmentName . '.local.json',
28
		] );
29
		self::checkIfPathsExist( ...$paths );
30
		return $paths;
31
	}
32
33
	private static function removeNonexistentOptionalPaths( string ...$paths ): array {
34
		if ( !file_exists( $paths[2] ) ) {
35
			array_splice( $paths, 2 );
36
		}
37
		return $paths;
38
	}
39
40
	private static function checkIfPathsExist( string ...$paths ): void {
41
		array_map(
42
			function ( $path ) {
43
				if ( !is_readable( $path ) ) {
44
					throw new \RuntimeException( 'Configuration file "' . $path . '" not found' );
45
				}
46
			},
47
			$paths
48
		);
49
	}
50
}
51