1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PhpCfdi\RfcLinc\Application\Providers; |
6
|
|
|
|
7
|
|
|
use PhpCfdi\RfcLinc\Application\Config; |
8
|
|
|
use Pimple\Container; |
9
|
|
|
use Pimple\ServiceProviderInterface; |
10
|
|
|
|
11
|
|
|
class ConfigServiceProvider implements ServiceProviderInterface |
12
|
|
|
{ |
13
|
|
|
/** @return string[] */ |
14
|
|
|
private $configFiles; |
15
|
|
|
|
16
|
13 |
|
public function __construct(string $configFile = '') |
17
|
|
|
{ |
18
|
13 |
|
if ('' === $configFile) { |
19
|
10 |
|
$this->configFiles = $this->defaultConfigFiles(); |
20
|
|
|
} else { |
21
|
3 |
|
$this->configFiles = [$configFile]; |
22
|
|
|
} |
23
|
13 |
|
} |
24
|
|
|
|
25
|
|
|
public function register(Container $container) |
26
|
|
|
{ |
27
|
2 |
|
$container['config'] = function (Container $container) { |
28
|
2 |
|
foreach ($this->configFiles() as $file) { |
29
|
2 |
|
$config = $this->tryCreateConfigFromFile($file); |
30
|
2 |
|
if ($config instanceof Config) { |
31
|
1 |
|
$container['debug'] = ! $config->isEnvironmentProduction(); |
32
|
2 |
|
return $config; |
33
|
|
|
} |
34
|
|
|
} |
35
|
1 |
|
throw new \RuntimeException('Cannot locate any valid config file'); |
36
|
|
|
}; |
37
|
9 |
|
} |
38
|
|
|
|
39
|
|
|
/** @return string[] */ |
40
|
4 |
|
public function configFiles(): array |
41
|
|
|
{ |
42
|
4 |
|
return $this->configFiles; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** @return string[] */ |
46
|
10 |
|
public function defaultConfigFiles(): array |
47
|
|
|
{ |
48
|
|
|
return [ |
49
|
10 |
|
getcwd() . '/.rfcLinc.php', |
50
|
10 |
|
getcwd() . 'rfcLinc.config.php', |
51
|
|
|
// __DIR__ is src/Application/Providers |
52
|
10 |
|
dirname(__DIR__, 3) . '/config/config.php', |
53
|
|
|
]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $filename |
58
|
|
|
* @return Config|null |
59
|
|
|
*/ |
60
|
4 |
|
public function tryCreateConfigFromFile(string $filename) |
61
|
|
|
{ |
62
|
|
|
try { |
63
|
4 |
|
return Config::createFromConfigFile($filename); |
64
|
2 |
|
} catch (\Throwable $exception) { |
65
|
2 |
|
return null; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|