Passed
Push — master ( be88e3...87c6b6 )
by Fran
04:17
created

Config::saveExtraParams()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

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

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