Passed
Push — master ( dfa0e8...921c67 )
by Fran
03:37
created

Config   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 96.97%

Importance

Changes 0
Metric Value
dl 0
loc 228
ccs 64
cts 66
cp 0.9697
rs 8.8
c 0
b 0
f 0
wmc 36
lcom 1
cbo 4

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A init() 0 7 2
A isLoaded() 0 3 1
B saveConfigParams() 0 14 6
B saveExtraParams() 0 13 5
A getDebugMode() 0 4 1
B isConfigured() 0 14 5
A checkTryToSaveConfig() 0 6 2
A get() 0 4 2
A dumpConfig() 0 4 2
A loadConfigData() 0 5 3
A clearConfig() 0 4 1
A getParam() 0 5 2
A save() 0 17 3
1
<?php
2
3
namespace PSFS\base\config;
4
5
6
use PSFS\base\Cache;
7
use PSFS\base\exception\ConfigException;
8
use PSFS\base\Logger;
9
use PSFS\base\Request;
10
use PSFS\base\types\SingletonTrait;
11
12
/**
13
 * Class Config
14
 * @package PSFS\base\config
15
 */
16
class Config
17
{
18
    use SingletonTrait;
19
    const DEFAULT_LANGUAGE = "es";
20
    const DEFAULT_ENCODE = "UTF-8";
21
    const DEFAULT_CTYPE = "text/html";
22
    const DEFAULT_DATETIMEZONE = "Europe/Madrid";
23
24
    const CONFIG_FILE = 'config.json';
25
26
    protected $config = array();
27
    static public $defaults = array(
28
        "db_host" => "localhost",
29
        "db_port" => "3306",
30
        "default_language" => "es_ES",
31
        "debug" => true,
32
        "front.version" => "v1",
33
        "version" => "v1",
34
    );
35
    static public $required = array('db_host', 'db_port', 'db_name', 'db_user', 'db_password', 'home_action', 'default_language', 'debug');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 139 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
36
    static public $encrypted = array('db_password');
37
    static public $optional = [
38
        'platform_name', // Platform name
39
        'restricted', // Restrict the web access
40
        'admin_login', // Enable web login for admin
41
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
42
        'logger.memory', // Enable log memory usage un traces
43
        'poweredBy', // Show PoweredBy header customized
44
        'author', // Author for auto generated files
45
        'author_email', // Author email for auto generated files
46
        'version', // Platform version(for cache purposes)
47
        'front.version', // Static resources version
48
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
49
        'pagination.limit', // Pagination limit for autogenerated api admin
50
        'api.secret', // Secret passphrase to securize the api
51
        'api.admin', // Enable de autogenerated api admin(wok)
52
        'log.level', // Max log level(default INFO)
53
        'admin_action', // Default admin url when access to /admin
54
        'cache.var', // Static cache var
55
        'twig.auto_reload', // Enable or disable auto reload templates for twig
56
        'modules.extend', // Variable for extending the current functionality
57
        'psfs.auth', // Variable for extending PSFS with the AUTH module
58
        'errors.strict', // Variable to trace all strict errors
59
        'psfs.memcache', // Add Memcache to prod cache process, ONLY for PROD environments
60
    ];
61
    protected $debug = false;
62
63
    /**
64
     * Config Constructor
65
     */
66 8
    public function __construct()
67
    {
68 8
        $this->init();
69 8
    }
70
71
    /**
72
     * Method that load the configuration data into the system
73
     * @return Config
74
     */
75 8
    protected function init()
76
    {
77 8
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
78 7
            $this->loadConfigData();
79
        }
80 8
        return $this;
81
    }
82
83
    /**
84
     * @return bool
85
     */
86 1
    public function isLoaded() {
87 1
        return !empty($this->config);
88
    }
89
90
    /**
91
     * Method that saves the configuration
92
     * @param array $data
93
     * @param array $extra
94
     * @return array
95
     */
96 2
    protected static function saveConfigParams(array $data, array $extra)
97
    {
98 2
        Logger::log('Saving required config parameters');
99
        //En caso de tener parámetros nuevos los guardamos
100 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
101 1
            foreach ($extra['label'] as $index => $field) {
102 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
103
                    /** @var $data array */
104 1
                    $data[$field] = $extra['value'][$index];
105
                }
106
            }
107
        }
108 2
        return $data;
109
    }
110
111
    /**
112
     * Method that saves the extra parameters into the configuration
113
     * @param array $data
114
     * @return array
115
     */
116 2
    protected static function saveExtraParams(array $data)
117
    {
118 2
        $final_data = array();
119 2
        if (count($data) > 0) {
120 2
            Logger::log('Saving extra configuration parameters');
121 2
            foreach ($data as $key => $value) {
122 2
                if (null !== $value || $value !== '') {
123 2
                    $final_data[$key] = $value;
124
                }
125
            }
126
        }
127 2
        return $final_data;
128
    }
129
130
    /**
131
     * Method that returns if the system is in debug mode
132
     * @return boolean
133
     */
134 6
    public function getDebugMode()
135
    {
136 6
        return $this->debug;
137
    }
138
139
    /**
140
     * Method that checks if the platform is proper configured
141
     * @return boolean
142
     */
143 2
    public function isConfigured()
144
    {
145 2
        Logger::log('Checking configuration');
146 2
        $configured = (count($this->config) > 0);
147 2
        if ($configured) {
148 1
            foreach (static::$required as $required) {
149 1
                if (!array_key_exists($required, $this->config)) {
150 1
                    $configured = false;
151 1
                    break;
152
                }
153
            }
154
        }
155 2
        return ($configured || $this->checkTryToSaveConfig());
156
    }
157
158
    /**
159
     * Method that check if the user is trying to save the config
160
     * @return bool
161
     */
162 2
    public function checkTryToSaveConfig()
163
    {
164 2
        $uri = Request::getInstance()->getRequestUri();
165 2
        $method = Request::getInstance()->getMethod();
166 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
167
    }
168
169
    /**
170
     * Method that saves all the configuration in the system
171
     *
172
     * @param array $data
173
     * @param array|null $extra
174
     * @return boolean
175
     */
176 2
    public static function save(array $data, array $extra = null)
177
    {
178 2
        $data = self::saveConfigParams($data, $extra);
179 2
        $final_data = self::saveExtraParams($data);
180 2
        $saved = false;
181
        try {
182 2
            $final_data = array_filter($final_data, function($key, $value) {
183 2
                return in_array($key, Config::$required) || !empty($value);
184 2
            }, ARRAY_FILTER_USE_BOTH);
185 2
            $saved = (false !== file_put_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, json_encode($final_data, JSON_PRETTY_PRINT)));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 150 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
186 2
            Config::getInstance()->loadConfigData();
187 2
            $saved = true;
188
        } catch (ConfigException $e) {
189
            Logger::log($e->getMessage(), LOG_ERR);
190
        }
191 2
        return $saved;
192
    }
193
194
    /**
195
     * Method that returns a config value
196
     * @param string $param
197
     * @param mixed $defaultValue
198
     *
199
     * @return mixed|null
200
     */
201 7
    public function get($param, $defaultValue = null)
202
    {
203 7
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
204
    }
205
206
    /**
207
     * Method that returns all the configuration
208
     * @return array
209
     */
210 2
    public function dumpConfig()
211
    {
212 2
        return $this->config ?: [];
213
    }
214
215
    /**
216
     * Method that reloads config file
217
     */
218 2
    public function loadConfigData()
219
    {
220 2
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
0 ignored issues
show
Documentation Bug introduced by
It seems like json_decode(file_get_con...FILE), true) ?: array() of type * is incompatible with the declared type array of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
221 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
222 2
    }
223
224
    /**
225
     * Clear configuration set
226
     */
227 1
    public function clearConfig()
228
    {
229 1
        $this->config = [];
230 1
    }
231
232
    /**
233
     * Static wrapper for extracting params
234
     * @param string $key
235
     * @param mixed|null $defaultValue
236
     * @return mixed|null
237
     */
238 6
    public static function getParam($key, $defaultValue = null)
239
    {
240 6
        $param = Config::getInstance()->get($key);
241 6
        return (null !== $param) ? $param : $defaultValue;
242
    }
243
}
244