Passed
Push — master ( c2bb1d...64c4d2 )
by Paweł
02:06
created

Env::loadConfigFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace pjpawel\LightApi\Component;
4
5
use pjpawel\LightApi\Exception\ProgrammerException;
6
7
class Env
8
{
9
10
    public const ENV_FILES = [
11
        'env.local.php',
12
        'env.php'
13
    ];
14
15
    /**
16
     * Get configuration from files in given directories
17
     *
18
     * @param string $dir
19
     * @param string $defaultConfigFile
20
     * @return array
21
     */
22
    public function getConfigFromEnv(string $dir, string $defaultConfigFile = 'config.php'): array
23
    {
24
        $config = [];
25
        $dir .= DIRECTORY_SEPARATOR;
26
        $files = scandir($dir);
27
        if (in_array($defaultConfigFile, $files)) {
28
            $config = $this->loadConfigFile($dir . $defaultConfigFile);
29
        }
30
        foreach (self::ENV_FILES as $file) {
31
            if (in_array($file, $files)) {
32
                $config = array_merge_recursive($this->loadConfigFile($dir . $file), $config);
33
            }
34
        }
35
        return $config;
36
    }
37
38
    /**
39
     * @param array $classConfig
40
     * @return object
41
     * @throws ProgrammerException|\ReflectionException
42
     */
43
    public function createClassFromConfig(array $classConfig): object
44
    {
45
        if (!isset($classConfig['class'])) {
46
            throw new ProgrammerException('Cannot create class from config');
47
        }
48
        return (new \ReflectionClass($classConfig['class']))->newInstanceArgs($classConfig['args'] ?? []);
49
    }
50
51
    /**
52
     * Method to get configuration array form a file
53
     *
54
     * @param string $filePath
55
     * @return array
56
     */
57
    public function loadConfigFile(string $filePath): array
58
    {
59
        return require $filePath;
60
    }
61
62
}