Completed
Push — master ( b9e797...6ab195 )
by Faiz
05:40
created

Config::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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