Passed
Push — master ( 8e9e8c...5c7da6 )
by Fran
03:59
created

Config::isLoaded()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
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\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
    ];
80
    protected $debug = false;
81
82
    /**
83
     * Method that load the configuration data into the system
84
     * @return Config
85
     */
86 1
    protected function init()
87
    {
88 1
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
89 1
            $this->loadConfigData();
90
        }
91 1
        return $this;
92
    }
93
94
    /**
95
     * @return bool
96
     */
97 1
    public function isLoaded() {
98 1
        return !empty($this->config);
99
    }
100
101
    /**
102
     * Method that saves the configuration
103
     * @param array $data
104
     * @param array $extra
105
     * @return array
106
     */
107 6
    protected static function saveConfigParams(array $data, $extra = null)
108
    {
109 6
        Logger::log('Saving required config parameters');
110
        //En caso de tener parámetros nuevos los guardamos
111 6
        if (!empty($extra) && array_key_exists('label', $extra) && is_array($extra['label'])) {
112 3
            foreach ($extra['label'] as $index => $field) {
113 3
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
114
                    /** @var $data array */
115 3
                    $data[$field] = $extra['value'][$index];
116
                }
117
            }
118
        }
119 6
        return $data;
120
    }
121
122
    /**
123
     * Method that saves the extra parameters into the configuration
124
     * @param array $data
125
     * @return array
126
     */
127 6
    protected static function saveExtraParams(array $data)
128
    {
129 6
        $finalData = array();
130 6
        if (count($data) > 0) {
131 6
            Logger::log('Saving extra configuration parameters');
132 6
            foreach ($data as $key => $value) {
133 6
                if (null !== $value || $value !== '') {
134 6
                    $finalData[$key] = $value;
135
                }
136
            }
137
        }
138 6
        return $finalData;
139
    }
140
141
    /**
142
     * Method that returns if the system is in debug mode
143
     * @return boolean
144
     */
145 4
    public function getDebugMode()
146
    {
147 4
        return $this->debug;
148
    }
149
150
    /**
151
     * @param bool $debug
152
     */
153 1
    public function setDebugMode($debug = true) {
154 1
        $this->debug = $debug;
155 1
        $this->config['debug'] = $this->debug;
156 1
    }
157
158
    /**
159
     * Method that checks if the platform is proper configured
160
     * @return boolean
161
     */
162 2
    public function isConfigured()
163
    {
164 2
        Inspector::stats('[Config] Checking configuration', Inspector::SCOPE_DEBUG);
165 2
        $configured = (count($this->config) > 0);
166 2
        if ($configured) {
167 1
            foreach (static::$required as $required) {
168 1
                if (!array_key_exists($required, $this->config)) {
169 1
                    $configured = false;
170 1
                    break;
171
                }
172
            }
173
        }
174 2
        return $configured || $this->checkTryToSaveConfig() || self::isTest();
175
    }
176
177
    /**
178
     * Method that check if the user is trying to save the config
179
     * @return bool
180
     */
181 3
    public function checkTryToSaveConfig()
182
    {
183 3
        $uri = Request::getInstance()->getRequestUri();
184 3
        $method = Request::getInstance()->getMethod();
185 3
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
186
    }
187
188
    /**
189
     * Method that saves all the configuration in the system
190
     *
191
     * @param array $data
192
     * @param array|null $extra
193
     * @return boolean
194
     */
195 6
    public static function save(array $data, $extra = null)
196
    {
197 6
        $data = self::saveConfigParams($data, $extra);
198 6
        $finalData = self::saveExtraParams($data);
199 6
        $saved = false;
200
        try {
201
            $finalData = array_filter($finalData, function($key, $value) {
202 6
                return in_array($key, self::$required, true) || !empty($value);
203 6
            }, ARRAY_FILTER_USE_BOTH);
204 6
            $saved = (false !== file_put_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, json_encode($finalData, JSON_PRETTY_PRINT)));
205 6
            self::getInstance()->loadConfigData();
206 6
            $saved = true;
207
        } catch (ConfigException $e) {
208
            Logger::log($e->getMessage(), LOG_ERR);
209
        }
210 6
        return $saved;
211
    }
212
213
    /**
214
     * Method that returns a config value
215
     * @param string $param
216
     * @param mixed $defaultValue
217
     *
218
     * @return mixed|null
219
     */
220 31
    public function get($param, $defaultValue = null)
221
    {
222 31
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
223
    }
224
225
    /**
226
     * Method that returns all the configuration
227
     * @return array
228
     */
229 6
    public function dumpConfig()
230
    {
231 6
        return $this->config ?: [];
232
    }
233
234
    /**
235
     * Method that reloads config file
236
     */
237 6
    public function loadConfigData()
238
    {
239 6
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
240 6
        $this->debug = array_key_exists('debug', $this->config) ? (bool)$this->config['debug'] : FALSE;
241 6
        if(array_key_exists('cache.var', $this->config)) {
242 1
            Security::getInstance()->setSessionKey('config.cache.var', $this->config['cache.var']);
243
        }
244 6
    }
245
246
    /**
247
     * Clear configuration set
248
     */
249 1
    public function clearConfig()
250
    {
251 1
        $this->config = [];
252 1
    }
253
254
    /**
255
     * Static wrapper for extracting params
256
     * @param string $key
257
     * @param mixed|null $defaultValue
258
     * @param string $module
259
     * @return mixed|null
260
     */
261 29
    public static function getParam($key, $defaultValue = null, $module = null)
262
    {
263 29
        if(null !== $module) {
264 1
            return self::getParam(strtolower($module) . '.' . $key, self::getParam($key, $defaultValue));
265
        }
266 29
        $param = self::getInstance()->get($key);
267 29
        return (null !== $param) ? $param : $defaultValue;
268
    }
269
270
    public static function initialize() {
271
        Config::getInstance();
272
        Logger::getInstance();
273
    }
274
}
275