Passed
Push — master ( 17804e...9c6a95 )
by Fran
06:14
created

Config::getDebugMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
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 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace PSFS\base\config;
4
5
6
use PSFS\base\Cache;
7
use PSFS\base\exception\ConfigException;
8
use PSFS\base\Logger;
9
use PSFS\base\Request;
10
use PSFS\base\types\SingletonTrait;
11
12
/**
13
 * Class Config
14
 * @package PSFS\base\config
15
 */
16
class Config
17
{
18
    use SingletonTrait;
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 = array();
27
    static public $defaults = array(
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 = 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...
36
    static public $encrypted = array('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.auto_reload', // 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
    ];
59
    protected $debug = false;
60
61
    /**
62
     * Config Constructor
63
     */
64 8
    public function __construct()
65
    {
66 8
        $this->init();
67 8
    }
68
69
    /**
70
     * Method that load the configuration data into the system
71
     * @return Config
72
     */
73 8
    protected function init()
74
    {
75 8
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE)) {
76 7
            $this->loadConfigData();
77
        }
78 8
        return $this;
79
    }
80
81
    /**
82
     * Method that saves the configuration
83
     * @param array $data
84
     * @param array $extra
85
     * @return array
86
     */
87 2
    protected static function saveConfigParams(array $data, array $extra)
88
    {
89 2
        Logger::log('Saving required config parameters');
90
        //En caso de tener parámetros nuevos los guardamos
91 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
92 1
            foreach ($extra['label'] as $index => $field) {
93 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
94
                    /** @var $data array */
95 1
                    $data[$field] = $extra['value'][$index];
96
                }
97
            }
98
        }
99 2
        return $data;
100
    }
101
102
    /**
103
     * Method that saves the extra parameters into the configuration
104
     * @param array $data
105
     * @return array
106
     */
107 2
    protected static function saveExtraParams(array $data)
108
    {
109 2
        $final_data = array();
110 2
        if (count($data) > 0) {
111 2
            Logger::log('Saving extra configuration parameters');
112 2
            foreach ($data as $key => $value) {
113 2
                if (null !== $value || $value !== '') {
114 2
                    $final_data[$key] = $value;
115
                }
116
            }
117
        }
118 2
        return $final_data;
119
    }
120
121
    /**
122
     * Method that returns if the system is in debug mode
123
     * @return boolean
124
     */
125 6
    public function getDebugMode()
126
    {
127 6
        return $this->debug;
128
    }
129
130
    /**
131
     * Method that checks if the platform is proper configured
132
     * @return boolean
133
     */
134 2
    public function isConfigured()
135
    {
136 2
        Logger::log('Checking configuration');
137 2
        $configured = (count($this->config) > 0);
138 2
        if ($configured) {
139 1
            foreach (static::$required as $required) {
140 1
                if (!array_key_exists($required, $this->config)) {
141 1
                    $configured = false;
142 1
                    break;
143
                }
144
            }
145
        }
146 2
        return ($configured || $this->checkTryToSaveConfig());
147
    }
148
149
    /**
150
     * Method that check if the user is trying to save the config
151
     * @return bool
152
     */
153 2
    public function checkTryToSaveConfig()
154
    {
155 2
        $uri = Request::getInstance()->getRequestUri();
156 2
        $method = Request::getInstance()->getMethod();
157 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
158
    }
159
160
    /**
161
     * Method that saves all the configuration in the system
162
     *
163
     * @param array $data
164
     * @param array|null $extra
165
     * @return boolean
166
     */
167 2
    public static function save(array $data, array $extra = null)
168
    {
169 2
        $data = self::saveConfigParams($data, $extra);
170 2
        $final_data = self::saveExtraParams($data);
171 2
        $saved = false;
172
        try {
173 2
            $final_data = array_filter($final_data, function($value) {
174 2
                return !empty($value);
175 2
            });
176 2
            Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE, $final_data, Cache::JSON, true);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 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...
177 2
            Config::getInstance()->loadConfigData();
178 2
            $saved = true;
179
        } catch (ConfigException $e) {
180
            Logger::log($e->getMessage(), LOG_ERR);
181
        }
182 2
        return $saved;
183
    }
184
185
    /**
186
     * Method that returns a config value
187
     * @param string $param
188
     * @param mixed $defaultValue
189
     *
190
     * @return mixed|null
191
     */
192 4
    public function get($param, $defaultValue = null)
193
    {
194 4
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
195
    }
196
197
    /**
198
     * Method that returns all the configuration
199
     * @return array
200
     */
201 2
    public function dumpConfig()
202
    {
203 2
        return $this->config ?: [];
204
    }
205
206
    /**
207
     * Method that reloads config file
208
     */
209 2
    public function loadConfigData()
210
    {
211 2
        $this->config = Cache::getInstance()->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . self::CONFIG_FILE,
0 ignored issues
show
Documentation Bug introduced by
It seems like \PSFS\base\Cache::getIns...:JSON, TRUE) ?: array() can also be of type string. However, the property $config is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
212 2
            Cache::JSON,
213 2
            TRUE) ?: [];
214 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
215 2
    }
216
217
    /**
218
     * Clear configuration set
219
     */
220 1
    public function clearConfig()
221
    {
222 1
        $this->config = [];
223 1
    }
224
225
    /**
226
     * Static wrapper for extracting params
227
     * @param string $key
228
     * @param mixed|null $defaultValue
229
     * @return mixed|null
230
     */
231 2
    public static function getParam($key, $defaultValue = null)
232
    {
233 2
        $param = Config::getInstance()->get($key);
234 2
        return (null !== $param) ? $param : $defaultValue;
235
    }
236
}
237