Completed
Push — master ( 1e296c...dace5d )
by Faiz
02:40
created

Config::buildConfig()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 7
cts 8
cp 0.875
rs 9.7
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 3.0175
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
        $this->configFile = realpath(__DIR__ . '/../../config/quran.php');
27
28
        // Merge our config with user config
29 93
        $result = array_replace_recursive((include $this->configFile), $config);
30
31
        // If function storage_path is exist (laravel), we update the path to laravel's storage path
32 93
        if (function_exists('storage_path') && php_sapi_name() !== 'cli') {
33
            $this->dataDir =  storage_path('app/' . $result['storage_path']);
34
        } else {
35 93
            $this->dataDir =  realpath(__DIR__ . '/../..') . '/' . $result['storage_path'];
36
        }
37
38 93
        $result['storage_path'] = $this->dataDir;
39 93
        return $result;
40
    }
41
42
    /**
43
     * Get the config variable.
44
     *
45
     * @param string $val Variable name
46
     * @return array|string Variable value
47
     */
48 123
    public function get($val)
49
    {
50 123
        $configs = explode('.', $val);
51 123
        $first = $this->config[array_shift($configs)];
52
53 123
        foreach ($configs as $config) {
54 87
            $first = $first[$config];
55
        }
56
57 123
        return $first;
58
    }
59
60
    /**
61
     * Return all configurations.
62
     *
63
     * @return array
64
     */
65 3
    public function all()
66
    {
67 3
        return $this->config;
68
    }
69
70 3
    public function addTranslation($id)
71
    {
72 3
        if (in_array($id, $this->config['translations'])) {
73
            return;
74
        }
75
76 3
        $configString = file_get_contents($this->configFile, true);
77 3
        $result = preg_replace('/([\'\"]translations[\'\"]\s+\=\>\s+\[[a-z\"\'\.\,\s]+)/i', "\\1, '$id'", $configString);
78 3
        file_put_contents($this->configFile, $result);
79 3
        array_push($this->config['translations'], $id);
80 3
    }
81
}
82