ConfigServiceProvider::configFiles()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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