-
Notifications
You must be signed in to change notification settings - Fork 58
/
Config.php
81 lines (71 loc) · 2 KB
/
Config.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Edge\QA;
use Symfony\Component\Yaml\Yaml;
class Config
{
private $configs = array();
public function __construct()
{
$this->loadCustomConfig(__DIR__ . '/../');
}
public function loadCustomConfig($directory, $isUserDirectory = false)
{
$configDir = $directory . '/';
$configFile = "{$configDir}.phpqa.yml";
if (file_exists($configFile)) {
$config = Yaml::parse(file_get_contents($configFile));
$this->configs = array_merge(
array($configDir => $config),
$this->configs
);
} elseif ($isUserDirectory) {
$this->throwInvalidPath('.phpqa.yml', $configFile);
}
}
public function value($path)
{
return $this->get(
$path,
function ($value) {
return $value;
}
);
}
public function path($path)
{
return $this->get(
$path,
function ($file, $dir) use ($path) {
$realpath = realpath("{$dir}{$file}");
if (!$realpath) {
$this->throwInvalidPath($path, "{$dir}{$file}");
}
return $realpath;
}
);
}
private function get($path, $extractor)
{
foreach ($this->configs as $dir => $config) {
$value = $this->findInConfig($config, $path);
if ($value !== null) {
return $extractor($value, $dir);
}
}
}
private function findInConfig(array $config, $path)
{
$result = $config;
foreach (explode('.', $path) as $key) {
if (!is_array($result) || !array_key_exists($key, $result)) {
return null;
}
$result = $result[$key];
}
return $result;
}
private function throwInvalidPath($source, $path)
{
throw new \RuntimeException("Invalid {$source} - '{$path}' does not exist.");
}
}