Test Failed
Push — master ( 1b7368...050678 )
by Fran
25:16 queued 22:49
created

Config::dumpConfig()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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