Passed
Push — master ( dd9457...9bc0cf )
by Fran
03:07
created

Config::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
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 6
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\traits\SingletonTrait;
8
use PSFS\base\types\traits\TestTrait;
9
10
/**
11
 * Class Config
12
 * @package PSFS\base\config
13
 */
14
class Config
15
{
16
    use SingletonTrait;
17
    use TestTrait;
18
19
    const DEFAULT_LANGUAGE = 'es';
20
    const DEFAULT_ENCODE = 'UTF-8';
21
    const DEFAULT_CTYPE = 'text/html';
22
    const DEFAULT_DATETIMEZONE = 'Europe/Madrid';
23
24
    const CONFIG_FILE = 'config.json';
25
26
    protected $config = [];
27
    static public $defaults = [
28
        'db.host' => 'localhost',
29
        'db.port' => '3306',
30
        'default.language' => 'es_ES',
31
        'debug' => true,
32
        'front.version' => 'v1',
33
        'version' => 'v1',
34
    ];
35
    static public $required = ['db.host', 'db.port', 'db.name', 'db.user', 'db.password', 'home.action', 'default.language', 'debug'];
36
    static public $encrypted = ['db.password'];
37
    static public $optional = [
38
        'platform.name', // Platform name
39
        'restricted', // Restrict the web access
40
        'admin.login', // Enable web login for admin
41
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
42
        'logger.memory', // Enable log memory usage un traces
43
        'poweredBy', // Show PoweredBy header customized
44
        'author', // Author for auto generated files
45
        'author.email', // Author email for auto generated files
46
        'version', // Platform version(for cache purposes)
47
        'front.version', // Static resources version
48
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
49
        'pagination.limit', // Pagination limit for autogenerated api admin
50
        'api.secret', // Secret passphrase to securize the api
51
        'api.admin', // Enable de autogenerated api admin(wok)
52
        'log.level', // Max log level(default INFO)
53
        'admin_action', // Default admin url when access to /admin
54
        'cache.var', // Static cache var
55
        'twig.autoreload', // Enable or disable auto reload templates for twig
56
        'modules.extend', // Variable for extending the current functionality
57
        'psfs.auth', // Variable for extending PSFS with the AUTH module
58
        'errors.strict', // Variable to trace all strict errors
59
        'psfs.memcache', // Add Memcache to prod cache process, ONLY for PROD environments
60
        'angular.protection', // Add an angular suggested prefix in order to avoid JSONP injections
61
        'cors.headers', // Add extra headers to the CORS check
62
        'json.encodeUTF8', // Encode the json response
63
        'cache.data.enable', // Enable data caching with PSFS
64
        'profiling.enable', // Enable the profiling headers
65
        'api.extrafields.compat', // Disbale retro compatibility with extra field mapping in api
66
        'output.json.strict_numbers', // Enable strict numbers in json responses
67
        'admin.version', // Determines the version for the admin ui
68
        'api.block.limit', // Determine the number of rows for bulk insert
69
        'api.field.types', // Extract __fields from api with their types
70
        'i18n.locales', // Default locales for any project
71
        'log.slack.hook', // Hook for slack traces
72
        'i18n.autogenerate', // Set PSFS auto generate i18n mode
73
        'resources.cdn.url', // CDN URL base path
74
        'api.field.type', // Field type for API dtos (phpName|camelName|camelName|fieldName) @see Propel TableMap calss
75
    ];
76
    protected $debug = false;
77
78
    /**
79
     * Method that load the configuration data into the system
80
     * @return Config
81
     */
82 2
    protected function init()
83
    {
84 2
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
85 1
            $this->loadConfigData();
86
        }
87 2
        return $this;
88
    }
89
90
    /**
91
     * @return bool
92
     */
93 2
    public function isLoaded() {
94 2
        return !empty($this->config);
95
    }
96
97
    /**
98
     * Method that saves the configuration
99
     * @param array $data
100
     * @param array $extra
101
     * @return array
102
     */
103 5
    protected static function saveConfigParams(array $data, array $extra)
104
    {
105 5
        Logger::log('Saving required config parameters');
106
        //En caso de tener parámetros nuevos los guardamos
107 5
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
108 3
            foreach ($extra['label'] as $index => $field) {
109 3
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
110
                    /** @var $data array */
111 3
                    $data[$field] = $extra['value'][$index];
112
                }
113
            }
114
        }
115 5
        return $data;
116
    }
117
118
    /**
119
     * Method that saves the extra parameters into the configuration
120
     * @param array $data
121
     * @return array
122
     */
123 5
    protected static function saveExtraParams(array $data)
124
    {
125 5
        $final_data = array();
126 5
        if (count($data) > 0) {
127 5
            Logger::log('Saving extra configuration parameters');
128 5
            foreach ($data as $key => $value) {
129 5
                if (null !== $value || $value !== '') {
130 5
                    $final_data[$key] = $value;
131
                }
132
            }
133
        }
134 5
        return $final_data;
135
    }
136
137
    /**
138
     * Method that returns if the system is in debug mode
139
     * @return boolean
140
     */
141 6
    public function getDebugMode()
142
    {
143 6
        return $this->debug;
144
    }
145
146
    /**
147
     * @param bool $debug
148
     */
149 1
    public function setDebugMode($debug = true) {
150 1
        $this->debug = $debug;
151 1
        $this->config['debug'] = $this->debug;
152 1
    }
153
154
    /**
155
     * Method that checks if the platform is proper configured
156
     * @return boolean
157
     */
158 2
    public function isConfigured()
159
    {
160 2
        Logger::log('Checking configuration');
161 2
        $configured = (count($this->config) > 0);
162 2
        if ($configured) {
163 1
            foreach (static::$required as $required) {
164 1
                if (!array_key_exists($required, $this->config)) {
165 1
                    $configured = false;
166 1
                    break;
167
                }
168
            }
169
        }
170 2
        return $configured || $this->checkTryToSaveConfig() || self::isTest();
171
    }
172
173
    /**
174
     * Method that check if the user is trying to save the config
175
     * @return bool
176
     */
177 3
    public function checkTryToSaveConfig()
178
    {
179 3
        $uri = Request::getInstance()->getRequestUri();
180 3
        $method = Request::getInstance()->getMethod();
181 3
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
182
    }
183
184
    /**
185
     * Method that saves all the configuration in the system
186
     *
187
     * @param array $data
188
     * @param array|null $extra
189
     * @return boolean
190
     */
191 5
    public static function save(array $data, array $extra = null)
192
    {
193 5
        $data = self::saveConfigParams($data, $extra);
0 ignored issues
show
Bug introduced by
It seems like $extra can also be of type null; however, parameter $extra of PSFS\base\config\Config::saveConfigParams() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

193
        $data = self::saveConfigParams($data, /** @scrutinizer ignore-type */ $extra);
Loading history...
194 5
        $final_data = self::saveExtraParams($data);
195 5
        $saved = false;
196
        try {
197
            $final_data = array_filter($final_data, function($key, $value) {
198 5
                return in_array($key, self::$required, true) || !empty($value);
199 5
            }, ARRAY_FILTER_USE_BOTH);
200 5
            $saved = (false !== file_put_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, json_encode($final_data, JSON_PRETTY_PRINT)));
201 5
            self::getInstance()->loadConfigData();
202 5
            $saved = true;
203
        } catch (ConfigException $e) {
204
            Logger::log($e->getMessage(), LOG_ERR);
205
        }
206 5
        return $saved;
207
    }
208
209
    /**
210
     * Method that returns a config value
211
     * @param string $param
212
     * @param mixed $defaultValue
213
     *
214
     * @return mixed|null
215
     */
216 23
    public function get($param, $defaultValue = null)
217
    {
218 23
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
219
    }
220
221
    /**
222
     * Method that returns all the configuration
223
     * @return array
224
     */
225 5
    public function dumpConfig()
226
    {
227 5
        return $this->config ?: [];
228
    }
229
230
    /**
231
     * Method that reloads config file
232
     */
233 5
    public function loadConfigData()
234
    {
235 5
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
236 5
        $this->debug = array_key_exists('debug', $this->config) ? (bool)$this->config['debug'] : FALSE;
237 5
    }
238
239
    /**
240
     * Clear configuration set
241
     */
242 1
    public function clearConfig()
243
    {
244 1
        $this->config = [];
245 1
    }
246
247
    /**
248
     * Static wrapper for extracting params
249
     * @param string $key
250
     * @param mixed|null $defaultValue
251
     * @param string $module
252
     * @return mixed|null
253
     */
254 23
    public static function getParam($key, $defaultValue = null, $module = null)
255
    {
256 23
        if(null !== $module) {
257 1
            return self::getParam(strtolower($module) . '.' . $key, self::getParam($key, $defaultValue));
258
        }
259 23
        $param = self::getInstance()->get($key);
260 23
        return (null !== $param) ? $param : $defaultValue;
261
    }
262
}
263