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