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

Config   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 92.59%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 0
dl 0
loc 77
ccs 25
cts 27
cp 0.9259
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A buildConfig() 0 17 3
A get() 0 11 2
A all() 0 4 1
A addTranslation() 0 11 2
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