Env   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 53
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A loadConfigFile() 0 3 1
A createClassFromConfig() 0 6 2
A getConfigFromEnv() 0 14 4
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
}