Passed
Push — master ( 84d9fe...0a2888 )
by Fran
04:03
created

Config::save()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0327

Importance

Changes 0
Metric Value
cc 3
eloc 14
nc 4
nop 2
dl 0
loc 17
ccs 11
cts 13
cp 0.8462
crap 3.0327
rs 9.4285
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');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 139 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
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
    ];
62
    protected $debug = false;
63
64
    /**
65
     * Method that load the configuration data into the system
66
     * @return Config
67
     */
68 1
    protected function init()
69
    {
70 1
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
71
            $this->loadConfigData();
72
        }
73 1
        return $this;
74
    }
75
76
    /**
77
     * @return bool
78
     */
79 1
    public function isLoaded() {
80 1
        return !empty($this->config);
81
    }
82
83
    /**
84
     * Method that saves the configuration
85
     * @param array $data
86
     * @param array $extra
87
     * @return array
88
     */
89 2
    protected static function saveConfigParams(array $data, array $extra)
90
    {
91 2
        Logger::log('Saving required config parameters');
92
        //En caso de tener parámetros nuevos los guardamos
93 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
94 1
            foreach ($extra['label'] as $index => $field) {
95 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
96
                    /** @var $data array */
97 1
                    $data[$field] = $extra['value'][$index];
98
                }
99
            }
100
        }
101 2
        return $data;
102
    }
103
104
    /**
105
     * Method that saves the extra parameters into the configuration
106
     * @param array $data
107
     * @return array
108
     */
109 2
    protected static function saveExtraParams(array $data)
110
    {
111 2
        $final_data = array();
112 2
        if (count($data) > 0) {
113 2
            Logger::log('Saving extra configuration parameters');
114 2
            foreach ($data as $key => $value) {
115 2
                if (null !== $value || $value !== '') {
116 2
                    $final_data[$key] = $value;
117
                }
118
            }
119
        }
120 2
        return $final_data;
121
    }
122
123
    /**
124
     * Method that returns if the system is in debug mode
125
     * @return boolean
126
     */
127 6
    public function getDebugMode()
128
    {
129 6
        return $this->debug;
130
    }
131
132
    /**
133
     * @param bool $debug
134
     */
135 1
    public function setDebugMode($debug = true) {
136 1
        $this->debug = $debug;
137 1
        $this->config['debug'] = $this->debug;
138 1
    }
139
140
    /**
141
     * Method that checks if the platform is proper configured
142
     * @return boolean
143
     */
144 2
    public function isConfigured()
145
    {
146 2
        Logger::log('Checking configuration');
147 2
        $configured = (count($this->config) > 0);
148 2
        if ($configured) {
149 1
            foreach (static::$required as $required) {
150 1
                if (!array_key_exists($required, $this->config)) {
151 1
                    $configured = false;
152 1
                    break;
153
                }
154
            }
155
        }
156 2
        return ($configured || $this->checkTryToSaveConfig());
157
    }
158
159
    /**
160
     * Method that check if the user is trying to save the config
161
     * @return bool
162
     */
163 3
    public function checkTryToSaveConfig()
164
    {
165 3
        $uri = Request::getInstance()->getRequestUri();
166 3
        $method = Request::getInstance()->getMethod();
167 3
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
168
    }
169
170
    /**
171
     * Method that saves all the configuration in the system
172
     *
173
     * @param array $data
174
     * @param array|null $extra
175
     * @return boolean
176
     */
177 2
    public static function save(array $data, array $extra = null)
178
    {
179 2
        $data = self::saveConfigParams($data, $extra);
180 2
        $final_data = self::saveExtraParams($data);
181 2
        $saved = false;
182
        try {
183 2
            $final_data = array_filter($final_data, function($key, $value) {
184 2
                return in_array($key, Config::$required) || !empty($value);
185 2
            }, ARRAY_FILTER_USE_BOTH);
186 2
            $saved = (false !== file_put_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, json_encode($final_data, JSON_PRETTY_PRINT)));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 150 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
187 2
            Config::getInstance()->loadConfigData();
188 2
            $saved = true;
189
        } catch (ConfigException $e) {
190
            Logger::log($e->getMessage(), LOG_ERR);
191
        }
192 2
        return $saved;
193
    }
194
195
    /**
196
     * Method that returns a config value
197
     * @param string $param
198
     * @param mixed $defaultValue
199
     *
200
     * @return mixed|null
201
     */
202 7
    public function get($param, $defaultValue = null)
203
    {
204 7
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
205
    }
206
207
    /**
208
     * Method that returns all the configuration
209
     * @return array
210
     */
211 2
    public function dumpConfig()
212
    {
213 2
        return $this->config ?: [];
214
    }
215
216
    /**
217
     * Method that reloads config file
218
     */
219 2
    public function loadConfigData()
220
    {
221 2
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
222 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
223 2
    }
224
225
    /**
226
     * Clear configuration set
227
     */
228 1
    public function clearConfig()
229
    {
230 1
        $this->config = [];
231 1
    }
232
233
    /**
234
     * Static wrapper for extracting params
235
     * @param string $key
236
     * @param mixed|null $defaultValue
237
     * @return mixed|null
238
     */
239 5
    public static function getParam($key, $defaultValue = null)
240
    {
241 5
        $param = Config::getInstance()->get($key);
242 5
        return (null !== $param) ? $param : $defaultValue;
243
    }
244
}
245