|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Churn\Configuration; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use Symfony\Component\Yaml\Exception\ParseException; |
|
9
|
|
|
use Symfony\Component\Yaml\Yaml; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @internal |
|
13
|
|
|
*/ |
|
14
|
|
|
class Loader |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @param string $confPath Path of the configuration file to load. |
|
18
|
|
|
* @param boolean $isDefaultValue Indicates whether $confPath contains the default value. |
|
19
|
|
|
* @throws InvalidArgumentException If the configuration file cannot be loaded. |
|
20
|
|
|
*/ |
|
21
|
|
|
public static function fromPath(string $confPath, bool $isDefaultValue): Config |
|
22
|
|
|
{ |
|
23
|
|
|
$originalConfPath = $confPath; |
|
24
|
|
|
$confPath = self::normalizePath($confPath); |
|
25
|
|
|
|
|
26
|
|
|
if (false !== $confPath && \is_readable($confPath)) { |
|
27
|
|
|
$yaml = self::loadYaml($confPath); |
|
28
|
|
|
|
|
29
|
|
|
return Config::create($yaml, $confPath); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
if ($isDefaultValue) { |
|
33
|
|
|
return Config::createFromDefaultValues(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
throw new InvalidArgumentException('The configuration file can not be read at ' . $originalConfPath); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param string $confPath Path to normalize. |
|
41
|
|
|
* @return string|false |
|
42
|
|
|
*/ |
|
43
|
|
|
private static function normalizePath(string $confPath) |
|
44
|
|
|
{ |
|
45
|
|
|
if (\is_dir($confPath)) { |
|
46
|
|
|
$confPath = \rtrim($confPath, '/\\') . '/churn.yml'; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return \realpath($confPath); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param string $confPath Path of the yaml file to load. |
|
54
|
|
|
* @return array<mixed> |
|
55
|
|
|
* @throws InvalidArgumentException If the configuration file is invalid. |
|
56
|
|
|
*/ |
|
57
|
|
|
private static function loadYaml(string $confPath): array |
|
58
|
|
|
{ |
|
59
|
|
|
$content = (string) \file_get_contents($confPath); |
|
60
|
|
|
|
|
61
|
|
|
try { |
|
62
|
|
|
$yaml = Yaml::parse($content) ?? []; |
|
63
|
|
|
} catch (ParseException $e) { |
|
64
|
|
|
$yaml = null; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
if (!\is_array($yaml)) { |
|
68
|
|
|
throw new InvalidArgumentException('The content of the configuration file is invalid'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return $yaml; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|