Passed
Push — master ( d9c7de...c204f0 )
by Fran
04:05
created

Config::isLoaded()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
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\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.auto_reload', // 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
    ];
59
    protected $debug = false;
60
61
    /**
62
     * Config Constructor
63
     */
64 1
    public function __construct()
65
    {
66 1
        $this->init();
67 1
    }
68
69
    /**
70
     * Method that load the configuration data into the system
71
     * @return Config
72
     */
73 1
    protected function init()
74
    {
75 1
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
76
            $this->loadConfigData();
77
        }
78 1
        return $this;
79
    }
80
81
    /**
82
     * @return bool
83
     */
84 1
    public function isLoaded() {
85 1
        return !empty($this->config);
86
    }
87
88
    /**
89
     * Method that saves the configuration
90
     * @param array $data
91
     * @param array $extra
92
     * @return array
93
     */
94 2
    protected static function saveConfigParams(array $data, array $extra)
95
    {
96 2
        Logger::log('Saving required config parameters');
97
        //En caso de tener parámetros nuevos los guardamos
98 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
99 1
            foreach ($extra['label'] as $index => $field) {
100 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
101
                    /** @var $data array */
102 1
                    $data[$field] = $extra['value'][$index];
103 1
                }
104 1
            }
105 1
        }
106 2
        return $data;
107
    }
108
109
    /**
110
     * Method that saves the extra parameters into the configuration
111
     * @param array $data
112
     * @return array
113
     */
114 2
    protected static function saveExtraParams(array $data)
115
    {
116 2
        $final_data = array();
117 2
        if (count($data) > 0) {
118 2
            Logger::log('Saving extra configuration parameters');
119 2
            foreach ($data as $key => $value) {
120 2
                if (null !== $value || $value !== '') {
121 2
                    $final_data[$key] = $value;
122 2
                }
123 2
            }
124 2
        }
125 2
        return $final_data;
126
    }
127
128
    /**
129
     * Method that returns if the system is in debug mode
130
     * @return boolean
131
     */
132 8
    public function getDebugMode()
133
    {
134 8
        return $this->debug;
135
    }
136
137
    /**
138
     * @param bool $debug
139
     */
140 1
    public function setDebugMode($debug = true) {
141 1
        $this->debug = $debug;
142 1
    }
143
144
    /**
145
     * Method that checks if the platform is proper configured
146
     * @return boolean
147
     */
148 2
    public function isConfigured()
149
    {
150 2
        Logger::log('Checking configuration');
151 2
        $configured = (count($this->config) > 0);
152 2
        if ($configured) {
153 1
            foreach (static::$required as $required) {
154 1
                if (!array_key_exists($required, $this->config)) {
155 1
                    $configured = false;
156 1
                    break;
157
                }
158 1
            }
159 1
        }
160 2
        return ($configured || $this->checkTryToSaveConfig());
161
    }
162
163
    /**
164
     * Method that check if the user is trying to save the config
165
     * @return bool
166
     */
167 2
    public function checkTryToSaveConfig()
168
    {
169 2
        $uri = Request::getInstance()->getRequestUri();
170 2
        $method = Request::getInstance()->getMethod();
171 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
172
    }
173
174
    /**
175
     * Method that saves all the configuration in the system
176
     *
177
     * @param array $data
178
     * @param array|null $extra
179
     * @return boolean
180
     */
181 2
    public static function save(array $data, array $extra = null)
182
    {
183 2
        $data = self::saveConfigParams($data, $extra);
184 2
        $final_data = self::saveExtraParams($data);
185 2
        $saved = false;
186
        try {
187 2
            $final_data = array_filter($final_data, function($key, $value) {
188 2
                return in_array($key, Config::$required) || !empty($value);
189 2
            }, ARRAY_FILTER_USE_BOTH);
190 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...
191 2
            Config::getInstance()->loadConfigData();
192 2
            $saved = true;
193 2
        } catch (ConfigException $e) {
194
            Logger::log($e->getMessage(), LOG_ERR);
195
        }
196 2
        return $saved;
197
    }
198
199
    /**
200
     * Method that returns a config value
201
     * @param string $param
202
     * @param mixed $defaultValue
203
     *
204
     * @return mixed|null
205
     */
206 6
    public function get($param, $defaultValue = null)
207
    {
208 6
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
209
    }
210
211
    /**
212
     * Method that returns all the configuration
213
     * @return array
214
     */
215 2
    public function dumpConfig()
216
    {
217 2
        return $this->config ?: [];
218
    }
219
220
    /**
221
     * Method that reloads config file
222
     */
223 2
    public function loadConfigData()
224
    {
225 2
        $this->config = json_decode(file_get_contents(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE), true) ?: [];
0 ignored issues
show
Documentation Bug introduced by
It seems like json_decode(file_get_con...FILE), true) ?: array() of type * is incompatible with the declared type array of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

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