Passed
Push — master ( f113c6...ab5b91 )
by Fran
02:46
created

Config::checkTryToSaveConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PSFS\base\config;
4
5
use PSFS\base\exception\ConfigException;
6
use PSFS\base\Logger;
7
use PSFS\base\Request;
8
use PSFS\base\Security;
9
use PSFS\base\types\helpers\Inspector;
10
use PSFS\base\types\traits\SingletonTrait;
11
use PSFS\base\types\traits\TestTrait;
12
13
/**
14
 * Class Config
15
 * @package PSFS\base\config
16
 */
17
class Config
18
{
19
    use SingletonTrait;
20
    use TestTrait;
21
22
    const DEFAULT_LANGUAGE = 'es';
23
    const DEFAULT_ENCODE = 'UTF-8';
24
    const DEFAULT_CTYPE = 'text/html';
25
    const DEFAULT_DATETIMEZONE = 'Europe/Madrid';
26
27
    const CONFIG_FILE = 'config.json';
28
29
    protected $config = [];
30
    static public $defaults = [
31
        'db.host' => 'localhost',
32
        'db.port' => '3306',
33
        'default.language' => 'es_ES',
34
        'debug' => true,
35
        'front.version' => 'v1',
36
        'version' => 'v1',
37
    ];
38
    static public $required = ['db.host', 'db.port', 'db.name', 'db.user', 'db.password', 'home.action', 'default.language', 'debug'];
39
    static public $encrypted = ['db.password'];
40
    static public $optional = [
41
        'platform.name', // Platform name
42
        'restricted', // Restrict the web access
43
        'admin.login', // Enable web login for admin
44
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
45
        'logger.memory', // Enable log memory usage un traces
46
        'poweredBy', // Show PoweredBy header customized
47
        'author', // Author for auto generated files
48
        'author.email', // Author email for auto generated files
49
        'version', // Platform version(for cache purposes)
50
        'front.version', // Static resources version
51
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
52
        'pagination.limit', // Pagination limit for autogenerated api admin
53
        'api.secret', // Secret passphrase to securize the api
54
        'api.admin', // Enable the autogenerated api admin(wok)
55
        'log.level', // Max log level(default INFO)
56
        'admin_action', // Default admin url when access to /admin
57
        'cache.var', // Static cache var
58
        'twig.autoreload', // Enable or disable auto reload templates for twig
59
        'modules.extend', // Variable for extending the current functionality
60
        'psfs.auth', // Variable for extending PSFS with the AUTH module
61
        'errors.strict', // Variable to trace all strict errors
62
        'psfs.memcache', // Add Memcache to prod cache process, ONLY for PROD environments
63
        'angular.protection', // Add an angular suggested prefix in order to avoid JSONP injections
64
        'cors.headers', // Add extra headers to the CORS check
65
        'json.encodeUTF8', // Encode the json response
66
        'cache.data.enable', // Enable data caching with PSFS
67
        'profiling.enable', // Enable the profiling headers
68
        'api.extrafields.compat', // Disbale retro compatibility with extra field mapping in api
69
        'output.json.strict_numbers', // Enable strict numbers in json responses
70
        'admin.version', // Determines the version for the admin ui
71
        'api.block.limit', // Determine the number of rows for bulk insert
72
        'api.field.types', // Extract __fields from api with their types
73
        'i18n.locales', // Default locales for any project
74
        'log.slack.hook', // Hook for slack traces
75
        'i18n.autogenerate', // Set PSFS auto generate i18n mode
76
        'resources.cdn.url', // CDN URL base path
77
        'api.field.case', // Field type for API dtos (phpName|camelName|camelName|fieldName) @see Propel TableMap class
78
        'route.404', // Set route for 404 pages
79
        'project.timezone', // Set the timezone for the timestamps in PSFS(Europe/madrid by default)
80
        'curl.returnTransfer', // Curl option CURLOPT_RETURNTRANSFER
81
        'curl.followLocation', // Curl option CURLOPT_FOLLOWLOCATION
82
        'curl.sslVerifyHost', // Curl option CURLOPT_SSL_VERIFYHOST
83
        'curl.sslVerifyPeer', // Curl option CURLOPT_SSL_VERIFYPEER
84
        'assets.obfuscate', // Allow to obfuscate and gzip js and css files
85
        'allow.double.slashes', // Allow // in url paths, allowed as default
86
        'default.log.path', // Default logger path
87
        'force.https', // Force https protocol for static resources
88
        'hide.modules', // Hide modules from menu, separated by comma
89
        'skip.route_generation', // Skip routes generation
90
    ];
91
    protected $debug = false;
92
93
    /**
94
     * Method that load the configuration data into the system
95
     * @return Config
96
     */
97 1
    protected function init()
98
    {
99 1
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
100 1
            $this->loadConfigData();
101
        }
102 1
        return $this;
103
    }
104
105
    /**
106
     * @return bool
107
     */
108 1
    public function isLoaded()
109
    {
110 1
        return !empty($this->config);
111
    }
112
113
    /**
114
     * Method that saves the configuration
115
     * @param array $data
116
     * @param array $extra
117
     * @return array
118
     */
119 8
    protected static function saveConfigParams(array $data, $extra = null)
120
    {
121 8
        Logger::log('Saving required config parameters');
122
        //En caso de tener parámetros nuevos los guardamos
123 8
        if (!empty($extra) && array_key_exists('label', $extra) && is_array($extra['label'])) {
124 3
            foreach ($extra['label'] as $index => $field) {
125 3
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
126
                    /** @var $data array */
127 3
                    $data[$field] = $extra['value'][$index];
128
                }
129
            }
130
        }
131 8
        return $data;
132
    }
133
134
    /**
135
     * Method that saves the extra parameters into the configuration
136
     * @param array $data
137
     * @return array
138
     */
139 8
    protected static function saveExtraParams(array $data)
140
    {
141 8
        $finalData = array();
142 8
        if (count($data) > 0) {
143 8
            Logger::log('Saving extra configuration parameters');
144 8
            foreach ($data as $key => $value) {
145 8
                if (null !== $value || $value !== '') {
146 8
                    $finalData[$key] = $value;
147
                }
148
            }
149
        }
150 8
        return $finalData;
151
    }
152
153
    /**
154
     * Method that returns if the system is in debug mode
155
     * @return boolean
156
     */
157 3
    public function getDebugMode()
158
    {
159 3
        return $this->debug;
160
    }
161
162
    /**
163
     * @param bool $debug
164
     */
165 2
    public function setDebugMode($debug = true)
166
    {
167 2
        $this->debug = $debug;
168 2
        $this->config['debug'] = $this->debug;
169
    }
170
171
    /**
172
     * Method that checks if the platform is proper configured
173
     * @return boolean
174
     */
175 2
    public function isConfigured()
176
    {
177 2
        Inspector::stats('[Config] Checking configuration', Inspector::SCOPE_DEBUG);
178 2
        $configured = (count($this->config) > 0);
179 2
        if ($configured) {
180 1
            foreach (static::$required as $required) {
181 1
                if (!array_key_exists($required, $this->config)) {
182 1
                    $configured = false;
183 1
                    break;
184
                }
185
            }
186
        }
187 2
        return $configured || $this->checkTryToSaveConfig() || self::isTest();
188
    }
189
190
    /**
191
     * Method that check if the user is trying to save the config
192
     * @return bool
193
     */
194 5
    public function checkTryToSaveConfig()
195
    {
196 5
        $uri = Request::getInstance()->getRequestUri();
197 5
        $method = Request::getInstance()->getMethod();
198 5
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
199
    }
200
201
    /**
202
     * Method that saves all the configuration in the system
203
     *
204
     * @param array $data
205
     * @param array|null $extra
206
     * @return boolean
207
     */
208 8
    public static function save(array $data, $extra = null)
209
    {
210 8
        $data = self::saveConfigParams($data, $extra);
211 8
        $finalData = self::saveExtraParams($data);
212 8
        $saved = false;
213
        try {
214 8
            $finalData = array_filter($finalData, function ($key, $value) {
215 8
                return in_array($key, self::$required, true) || !empty($value);
216 8
            }, ARRAY_FILTER_USE_BOTH);
217 8
            $saved = (false !== file_put_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, json_encode($finalData, JSON_PRETTY_PRINT)));
218 8
            self::getInstance()->loadConfigData();
219 8
            $saved = true;
220
        } catch (ConfigException $e) {
221
            Logger::log($e->getMessage(), LOG_ERR);
222
        }
223 8
        return $saved;
224
    }
225
226
    /**
227
     * Method that returns a config value
228
     * @param string $param
229
     * @param mixed $defaultValue
230
     *
231
     * @return mixed|null
232
     */
233 39
    public function get($param, $defaultValue = null)
234
    {
235 39
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
236
    }
237
238
    /**
239
     * Method that returns all the configuration
240
     * @return array
241
     */
242 8
    public function dumpConfig()
243
    {
244 8
        return $this->config ?: [];
245
    }
246
247
    /**
248
     * Method that reloads config file
249
     */
250 8
    public function loadConfigData()
251
    {
252 8
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
253 8
        $this->debug = array_key_exists('debug', $this->config) ? (bool)$this->config['debug'] : FALSE;
254 8
        if (array_key_exists('cache.var', $this->config)) {
255 1
            Security::getInstance()->setSessionKey('config.cache.var', $this->config['cache.var']);
256
        }
257
    }
258
259
    /**
260
     * Clear configuration set
261
     */
262 1
    public function clearConfig()
263
    {
264 1
        $this->config = [];
265
    }
266
267
    /**
268
     * Static wrapper for extracting params
269
     * @param string $key
270
     * @param mixed|null $defaultValue
271
     * @param string $module
272
     * @return mixed|null
273
     */
274 37
    public static function getParam($key, $defaultValue = null, $module = null)
275
    {
276 37
        if (null !== $module) {
277 2
            return self::getParam(strtolower($module) . '.' . $key, self::getParam($key, $defaultValue));
278
        }
279 37
        $param = self::getInstance()->get($key);
280 37
        return (null !== $param) ? $param : $defaultValue;
281
    }
282
283 1
    public static function initialize()
284
    {
285 1
        Config::getInstance();
286 1
        Logger::getInstance();
287
    }
288
289
    public static function clearConfigFiles(): bool
290
    {
291
        $configs = ['domains.json', 'urls.json'];
292
        $done = true;
293
        foreach ($configs as $configFile) {
294
            if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . $configFile)) {
295
                if (!unlink(CONFIG_DIR . DIRECTORY_SEPARATOR . $configFile)) {
296
                    $done = false;
297
                }
298
            }
299
        }
300
        return $done;
301
    }
302
}
303