Passed
Push — master ( 404bb4...8b694f )
by Fran
02:56
created

Config::getParam()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 3
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 3.072
rs 9.6666
c 0
b 0
f 0
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
        'profiling.enable', // Enable the profiling headers
63
        'api.extrafields.compat', // Disbale retro compatibility with extra field mapping in api
64
        'output.json.strict_numbers', // Enable strict numbers in json responses
65
        'admin.version', // Determines the version for the admin ui
66
    ];
67
    protected $debug = false;
68
69
    /**
70
     * Method that load the configuration data into the system
71
     * @return Config
72
     */
73 1
    protected function init()
74
    {
75 1
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
76
            $this->loadConfigData();
77
        }
78 1
        return $this;
79
    }
80
81
    /**
82
     * @return bool
83
     */
84 1
    public function isLoaded() {
85 1
        return !empty($this->config);
86
    }
87
88
    /**
89
     * Method that saves the configuration
90
     * @param array $data
91
     * @param array $extra
92
     * @return array
93
     */
94 4
    protected static function saveConfigParams(array $data, array $extra)
95
    {
96 4
        Logger::log('Saving required config parameters');
97
        //En caso de tener parámetros nuevos los guardamos
98 4
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
99 2
            foreach ($extra['label'] as $index => $field) {
100 2
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
101
                    /** @var $data array */
102 2
                    $data[$field] = $extra['value'][$index];
103
                }
104
            }
105
        }
106 4
        return $data;
107
    }
108
109
    /**
110
     * Method that saves the extra parameters into the configuration
111
     * @param array $data
112
     * @return array
113
     */
114 4
    protected static function saveExtraParams(array $data)
115
    {
116 4
        $final_data = array();
117 4
        if (count($data) > 0) {
118 4
            Logger::log('Saving extra configuration parameters');
119 4
            foreach ($data as $key => $value) {
120 4
                if (null !== $value || $value !== '') {
121 4
                    $final_data[$key] = $value;
122
                }
123
            }
124
        }
125 4
        return $final_data;
126
    }
127
128
    /**
129
     * Method that returns if the system is in debug mode
130
     * @return boolean
131
     */
132 7
    public function getDebugMode()
133
    {
134 7
        return $this->debug;
135
    }
136
137
    /**
138
     * @param bool $debug
139
     */
140 1
    public function setDebugMode($debug = true) {
141 1
        $this->debug = $debug;
142 1
        $this->config['debug'] = $this->debug;
143 1
    }
144
145
    /**
146
     * Method that checks if the platform is proper configured
147
     * @return boolean
148
     */
149 2
    public function isConfigured()
150
    {
151 2
        Logger::log('Checking configuration');
152 2
        $configured = (count($this->config) > 0);
153 2
        if ($configured) {
154 1
            foreach (static::$required as $required) {
155 1
                if (!array_key_exists($required, $this->config)) {
156 1
                    $configured = false;
157 1
                    break;
158
                }
159
            }
160
        }
161 2
        return ($configured || $this->checkTryToSaveConfig());
162
    }
163
164
    /**
165
     * Method that check if the user is trying to save the config
166
     * @return bool
167
     */
168 2
    public function checkTryToSaveConfig()
169
    {
170 2
        $uri = Request::getInstance()->getRequestUri();
171 2
        $method = Request::getInstance()->getMethod();
172 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
173
    }
174
175
    /**
176
     * Method that saves all the configuration in the system
177
     *
178
     * @param array $data
179
     * @param array|null $extra
180
     * @return boolean
181
     */
182 4
    public static function save(array $data, array $extra = null)
183
    {
184 4
        $data = self::saveConfigParams($data, $extra);
185 4
        $final_data = self::saveExtraParams($data);
186 4
        $saved = false;
187
        try {
188 4
            $final_data = array_filter($final_data, function($key, $value) {
189 4
                return in_array($key, Config::$required) || !empty($value);
190 4
            }, ARRAY_FILTER_USE_BOTH);
191 4
            $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...
192 4
            Config::getInstance()->loadConfigData();
193 4
            $saved = true;
194
        } catch (ConfigException $e) {
195
            Logger::log($e->getMessage(), LOG_ERR);
196
        }
197 4
        return $saved;
198
    }
199
200
    /**
201
     * Method that returns a config value
202
     * @param string $param
203
     * @param mixed $defaultValue
204
     *
205
     * @return mixed|null
206
     */
207 21
    public function get($param, $defaultValue = null)
208
    {
209 21
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
210
    }
211
212
    /**
213
     * Method that returns all the configuration
214
     * @return array
215
     */
216 4
    public function dumpConfig()
217
    {
218 4
        return $this->config ?: [];
219
    }
220
221
    /**
222
     * Method that reloads config file
223
     */
224 4
    public function loadConfigData()
225
    {
226 4
        $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...
227 4
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
228 4
    }
229
230
    /**
231
     * Clear configuration set
232
     */
233 1
    public function clearConfig()
234
    {
235 1
        $this->config = [];
236 1
    }
237
238
    /**
239
     * Static wrapper for extracting params
240
     * @param string $key
241
     * @param mixed|null $defaultValue
242
     * @param string $module
0 ignored issues
show
Documentation introduced by
Should the type for parameter $module not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
243
     * @return mixed|null
244
     */
245 21
    public static function getParam($key, $defaultValue = null, $module = null)
246
    {
247 21
        if(null !== $module) {
248
            return self::getParam(strtolower($module) . '.' . $key, self::getParam($key, $defaultValue));
249
        } else {
250 21
            $param = Config::getInstance()->get($key);
251 21
            return (null !== $param) ? $param : $defaultValue;
252
        }
253
    }
254
}
255