Completed
Push — master ( 085d7d...5e056d )
by Faiz
03:07
created

Config::buildConfig()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.072

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 8
cts 10
cp 0.8
rs 9.584
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3.072
1
<?php
2
3
namespace FaizShukri\Quran\Supports;
4
5
class Config
6
{
7
    private $config;
8
9
    public $configFile;
10
11
    public $dataDir;
12
13 93
    public function __construct(array $config = [])
14
    {
15 93
        $this->config = $this->buildConfig($config);
16 93
    }
17
18
    /**
19
     * Build a config array. Merge user defined config with our default config.
20
     *
21
     * @param array $config User defined config
22
     * @return array New configuration array
23
     */
24 93
    private function buildConfig(array $config = [])
25
    {
26 93
        if (function_exists('config_path')) {
27
            $this->configFile = config_path('quran.php');
28
        } else {
29 93
            $this->configFile = realpath(__DIR__ . '/../../config/quran.php');
30
        }
31
32
        // Merge our config with user config
33 93
        $result = array_replace_recursive((include $this->configFile), $config);
34
35
        // If function storage_path is exist (laravel), we update the path to laravel's storage path
36 93
        if (function_exists('storage_path')) {
37
            $this->dataDir =  storage_path('app/' . $result['storage_path']);
38
        } else {
39 93
            $this->dataDir =  realpath(__DIR__ . '/../..') . '/' . $result['storage_path'];
40
        }
41
42 93
        $result['storage_path'] = $this->dataDir;
43 93
        return $result;
44
    }
45
46
    /**
47
     * Get the config variable.
48
     *
49
     * @param string $val Variable name
50
     * @return array|string Variable value
51
     */
52 123
    public function get($val)
53
    {
54 123
        $configs = explode('.', $val);
55 123
        $first = $this->config[array_shift($configs)];
56
57 123
        foreach ($configs as $config) {
58 87
            $first = $first[$config];
59
        }
60
61 123
        return $first;
62
    }
63
64
    /**
65
     * Return all configurations.
66
     *
67
     * @return array
68
     */
69 3
    public function all()
70
    {
71 3
        return $this->config;
72
    }
73
74 3
    public function addTranslation($id)
75
    {
76 3
        if (in_array($id, $this->config['translations'])) {
77
            return;
78
        }
79
80 3
        $configString = file_get_contents($this->configFile, true);
81 3
        $result = preg_replace('/([\'\"]translations[\'\"]\s+\=\>\s+\[[a-z\"\'\.\,\s]+)/i', "\\1, '$id'", $configString);
82 3
        file_put_contents($this->configFile, $result);
83 3
        array_push($this->config['translations'], $id);
84 3
    }
85
}
86