Passed
Push — master ( bf5903...f5157c )
by Fran
04:43
created

Config   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 233
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95.52%

Importance

Changes 0
Metric Value
dl 0
loc 233
ccs 64
cts 67
cp 0.9552
rs 8.8
c 0
b 0
f 0
wmc 36
lcom 1
cbo 4

14 Methods

Rating   Name   Duplication   Size   Complexity  
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
A setDebugMode() 0 4 1
B isConfigured() 0 14 5
A checkTryToSaveConfig() 0 6 2
A save() 0 17 3
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
1
<?php
2
namespace PSFS\base\config;
3
4
use PSFS\base\exception\ConfigException;
5
use PSFS\base\Logger;
6
use PSFS\base\Request;
7
use PSFS\base\types\traits\SingletonTrait;
8
9
/**
10
 * Class Config
11
 * @package PSFS\base\config
12
 */
13
class Config
14
{
15
    use SingletonTrait;
16
17
    const DEFAULT_LANGUAGE = "es";
18
    const DEFAULT_ENCODE = "UTF-8";
19
    const DEFAULT_CTYPE = "text/html";
20
    const DEFAULT_DATETIMEZONE = "Europe/Madrid";
21
22
    const CONFIG_FILE = 'config.json';
23
24
    protected $config = array();
25
    static public $defaults = array(
26
        "db.host" => "localhost",
27
        "db.port" => "3306",
28
        "default.language" => "es_ES",
29
        "debug" => true,
30
        "front.version" => "v1",
31
        "version" => "v1",
32
    );
33
    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...
34
    static public $encrypted = array('db.password');
35
    static public $optional = [
36
        'platform.name', // Platform name
37
        'restricted', // Restrict the web access
38
        'admin.login', // Enable web login for admin
39
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
40
        'logger.memory', // Enable log memory usage un traces
41
        'poweredBy', // Show PoweredBy header customized
42
        'author', // Author for auto generated files
43
        'author.email', // Author email for auto generated files
44
        'version', // Platform version(for cache purposes)
45
        'front.version', // Static resources version
46
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
47
        'pagination.limit', // Pagination limit for autogenerated api admin
48
        'api.secret', // Secret passphrase to securize the api
49
        'api.admin', // Enable de autogenerated api admin(wok)
50
        'log.level', // Max log level(default INFO)
51
        'admin_action', // Default admin url when access to /admin
52
        'cache.var', // Static cache var
53
        'twig.autoreload', // Enable or disable auto reload templates for twig
54
        'modules.extend', // Variable for extending the current functionality
55
        'psfs.auth', // Variable for extending PSFS with the AUTH module
56
        'errors.strict', // Variable to trace all strict errors
57
        'psfs.memcache', // Add Memcache to prod cache process, ONLY for PROD environments
58
        'angular.protection', // Add an angular suggested prefix in order to avoid JSONP injections
59
        'cors.headers', // Add extra headers to the CORS check
60
        'json.encodeUTF8', // Encode the json response
61
        'cache.data.enable', // Enable data caching with PSFS
62
    ];
63
    protected $debug = false;
64
65
    /**
66
     * Method that load the configuration data into the system
67
     * @return Config
68
     */
69 1
    protected function init()
70
    {
71 1
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
72
            $this->loadConfigData();
73
        }
74 1
        return $this;
75
    }
76
77
    /**
78
     * @return bool
79
     */
80 1
    public function isLoaded() {
81 1
        return !empty($this->config);
82
    }
83
84
    /**
85
     * Method that saves the configuration
86
     * @param array $data
87
     * @param array $extra
88
     * @return array
89
     */
90 3
    protected static function saveConfigParams(array $data, array $extra)
91
    {
92 3
        Logger::log('Saving required config parameters');
93
        //En caso de tener parámetros nuevos los guardamos
94 3
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
95 2
            foreach ($extra['label'] as $index => $field) {
96 2
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
97
                    /** @var $data array */
98 2
                    $data[$field] = $extra['value'][$index];
99
                }
100
            }
101
        }
102 3
        return $data;
103
    }
104
105
    /**
106
     * Method that saves the extra parameters into the configuration
107
     * @param array $data
108
     * @return array
109
     */
110 3
    protected static function saveExtraParams(array $data)
111
    {
112 3
        $final_data = array();
113 3
        if (count($data) > 0) {
114 3
            Logger::log('Saving extra configuration parameters');
115 3
            foreach ($data as $key => $value) {
116 3
                if (null !== $value || $value !== '') {
117 3
                    $final_data[$key] = $value;
118
                }
119
            }
120
        }
121 3
        return $final_data;
122
    }
123
124
    /**
125
     * Method that returns if the system is in debug mode
126
     * @return boolean
127
     */
128 7
    public function getDebugMode()
129
    {
130 7
        return $this->debug;
131
    }
132
133
    /**
134
     * @param bool $debug
135
     */
136 1
    public function setDebugMode($debug = true) {
137 1
        $this->debug = $debug;
138 1
        $this->config['debug'] = $this->debug;
139 1
    }
140
141
    /**
142
     * Method that checks if the platform is proper configured
143
     * @return boolean
144
     */
145 2
    public function isConfigured()
146
    {
147 2
        Logger::log('Checking configuration');
148 2
        $configured = (count($this->config) > 0);
149 2
        if ($configured) {
150 1
            foreach (static::$required as $required) {
151 1
                if (!array_key_exists($required, $this->config)) {
152 1
                    $configured = false;
153 1
                    break;
154
                }
155
            }
156
        }
157 2
        return ($configured || $this->checkTryToSaveConfig());
158
    }
159
160
    /**
161
     * Method that check if the user is trying to save the config
162
     * @return bool
163
     */
164 2
    public function checkTryToSaveConfig()
165
    {
166 2
        $uri = Request::getInstance()->getRequestUri();
167 2
        $method = Request::getInstance()->getMethod();
168 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
169
    }
170
171
    /**
172
     * Method that saves all the configuration in the system
173
     *
174
     * @param array $data
175
     * @param array|null $extra
176
     * @return boolean
177
     */
178 3
    public static function save(array $data, array $extra = null)
179
    {
180 3
        $data = self::saveConfigParams($data, $extra);
181 3
        $final_data = self::saveExtraParams($data);
182 3
        $saved = false;
183
        try {
184 3
            $final_data = array_filter($final_data, function($key, $value) {
185 3
                return in_array($key, Config::$required) || !empty($value);
186 3
            }, ARRAY_FILTER_USE_BOTH);
187 3
            $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...
188 3
            Config::getInstance()->loadConfigData();
189 3
            $saved = true;
190
        } catch (ConfigException $e) {
191
            Logger::log($e->getMessage(), LOG_ERR);
192
        }
193 3
        return $saved;
194
    }
195
196
    /**
197
     * Method that returns a config value
198
     * @param string $param
199
     * @param mixed $defaultValue
200
     *
201
     * @return mixed|null
202
     */
203 20
    public function get($param, $defaultValue = null)
204
    {
205 20
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
206
    }
207
208
    /**
209
     * Method that returns all the configuration
210
     * @return array
211
     */
212 2
    public function dumpConfig()
213
    {
214 2
        return $this->config ?: [];
215
    }
216
217
    /**
218
     * Method that reloads config file
219
     */
220 3
    public function loadConfigData()
221
    {
222 3
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
0 ignored issues
show
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...
223 3
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
224 3
    }
225
226
    /**
227
     * Clear configuration set
228
     */
229 1
    public function clearConfig()
230
    {
231 1
        $this->config = [];
232 1
    }
233
234
    /**
235
     * Static wrapper for extracting params
236
     * @param string $key
237
     * @param mixed|null $defaultValue
238
     * @return mixed|null
239
     */
240 20
    public static function getParam($key, $defaultValue = null)
241
    {
242 20
        $param = Config::getInstance()->get($key);
243 20
        return (null !== $param) ? $param : $defaultValue;
244
    }
245
}
246