Passed
Push — master ( 74847c...ad33a7 )
by Fran
03:09
created

Config::getParam()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
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
use PSFS\controller\UserController;
12
13
/**
14
 * Class Config
15
 * @package PSFS\base\config
16
 */
17
class Config
18
{
19
    use SingletonTrait;
20
    const DEFAULT_LANGUAGE = "es";
21
    const DEFAULT_ENCODE = "UTF-8";
22
    const DEFAULT_CTYPE = "text/html";
23
    const DEFAULT_DATETIMEZONE = "Europe/Madrid";
24
25
    protected $config = array();
26
    static public $defaults = array(
27
        "db_host" => "localhost",
28
        "db_port" => "3306",
29
        "default_language" => "es_ES",
30
        "debug" => true,
31
        "front.version" => "v1",
32
        "version" => "v1",
33
    );
34
    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...
35
    static public $encrypted = array('db_password');
36
    static public $optional = [
37
        'platform_name', // Platform name
38
        'restricted', // Restrict the web access
39
        'admin_login', // Enable web login for admin
40
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
41
        'logger.memory', // Enable log memory usage un traces
42
        'poweredBy', // Show PoweredBy header customized
43
        'author', // Author for auto generated files
44
        'author_email', // Author email for auto generated files
45
        'version', // Platform version(for cache purposes)
46
        'front.version', // Static resources version
47
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
48
        'pagination.limit', // Pagination limit for autogenerated api admin
49
        'api.secret', // Secret passphrase to securize the api
50
        'api.admin', // Enable de autogenerated api admin(wok)
51
        'log.level', // Max log level(default INFO)
52
        'admin_action', // Default admin url when access to /admin
53
        'cache.var', // Static cache var
54
        'twig.auto_reload' // Enable or disable auto reload templates for twig
55
    ];
56
    protected $debug = false;
57
58
    /**
59
     * Config Constructor
60
     */
61 8
    public function __construct()
62
    {
63 8
        $this->init();
64 8
    }
65
66
    /**
67
     * Method that load the configuration data into the system
68
     * @return Config
69
     */
70 8
    protected function init()
71
    {
72 8
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json")) {
73 7
            $this->loadConfigData();
74 7
        }
75 8
        return $this;
76
    }
77
78
    /**
79
     * Method that saves the configuration
80
     * @param array $data
81
     * @param array $extra
82
     * @return array
83
     */
84 2
    protected static function saveConfigParams(array $data, array $extra)
85
    {
86 2
        Logger::log('Saving required config parameters');
87
        //En caso de tener parámetros nuevos los guardamos
88 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
89 1
            foreach ($extra['label'] as $index => $field) {
90 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
91
                    /** @var $data array */
92 1
                    $data[$field] = $extra['value'][$index];
93 1
                }
94 1
            }
95 1
        }
96 2
        return $data;
97
    }
98
99
    /**
100
     * Method that saves the extra parameters into the configuration
101
     * @param array $data
102
     * @return array
103
     */
104 2
    protected static function saveExtraParams(array $data)
105
    {
106 2
        $final_data = array();
107 2
        if (count($data) > 0) {
108 2
            Logger::log('Saving extra configuration parameters');
109 2
            foreach ($data as $key => $value) {
110 2
                if (null !== $value || $value !== '') {
111 2
                    $final_data[$key] = $value;
112 2
                }
113 2
            }
114 2
        }
115 2
        return $final_data;
116
    }
117
118
    /**
119
     * Method that returns if the system is in debug mode
120
     * @return boolean
121
     */
122 6
    public function getDebugMode()
123
    {
124 6
        return $this->debug;
125
    }
126
127
    /**
128
     * Method that returns the cache path
129
     * @return string
130
     */
131 2
    public function getCachePath()
132
    {
133 2
        return CACHE_DIR;
134
    }
135
136
    /**
137
     * Method that returns the templates path
138
     * @return string
139
     */
140 2
    public function getTemplatePath()
141
    {
142 2
        $path = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 140 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...
143 2
        return realpath($path);
144
    }
145
146
    /**
147
     * Method that checks if the platform is proper configured
148
     * @return boolean
149
     */
150 2
    public function isConfigured()
151
    {
152 2
        Logger::log('Checking configuration');
153 2
        $configured = (count($this->config) > 0);
154 2
        if ($configured) {
155 1
            foreach (static::$required as $required) {
156 1
                if (!array_key_exists($required, $this->config)) {
157 1
                    $configured = false;
158 1
                    break;
159
                }
160 1
            }
161 1
        }
162 2
        return ($configured || $this->checkTryToSaveConfig());
163
    }
164
165
    /**
166
     * Method that check if the user is trying to save the config
167
     * @return bool
168
     */
169 2
    public function checkTryToSaveConfig()
170
    {
171 2
        $uri = Request::getInstance()->getRequestUri();
172 2
        $method = Request::getInstance()->getMethod();
173 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
174
    }
175
176
    /**
177
     * Method that saves all the configuration in the system
178
     *
179
     * @param array $data
180
     * @param array|null $extra
181
     * @return boolean
182
     */
183 2
    public static function save(array $data, array $extra = null)
184
    {
185 2
        $data = self::saveConfigParams($data, $extra);
186 2
        $final_data = self::saveExtraParams($data);
187 2
        $saved = false;
188
        try {
189 2
            Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json", $final_data, Cache::JSON, true);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 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...
190 2
            Config::getInstance()->loadConfigData();
191 2
            $saved = true;
192 2
        } catch (ConfigException $e) {
193
            Logger::log($e->getMessage(), LOG_ERR);
194
        }
195 2
        return $saved;
196
    }
197
198
    /**
199
     * Method that returns a config value
200
     * @param string $param
201
     *
202
     * @return mixed|null
203
     */
204 4
    public function get($param)
205
    {
206 4
        return array_key_exists($param, $this->config) ? $this->config[$param] : null;
207
    }
208
209
    /**
210
     * Method that returns all the configuration
211
     * @return array
212
     */
213 2
    public function dumpConfig()
214
    {
215 2
        return $this->config ?: [];
216 1
    }
217
218
    /**
219
     * Method that returns the Propel ORM parameters to setup the models
220
     * @return array|null
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
221
     */
222 1
    public function getPropelParams()
223
    {
224 1
        return Cache::getInstance()->getDataFromFile(__DIR__ . DIRECTORY_SEPARATOR . 'properties.json', Cache::JSON, true);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 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...
225
    }
226
227
    /**
228
     * Method that creates any parametrized path
229
     * @param string $dir
230
     * throws ConfigException
231
     */
232 7
    public static function createDir($dir)
233
    {
234
        try {
235 7
            if (!is_dir($dir) && @mkdir($dir, 0775, true) === false) {
236
                throw new \Exception(_('Can\'t create directory ') . $dir);
237
            }
238 7
        } catch (\Exception $e) {
239
            Logger::log($e->getMessage(), LOG_WARNING);
240
            if (!file_exists(dirname($dir))) {
241
                throw new ConfigException($e->getMessage() . $dir);
242
            }
243
        }
244 7
    }
245
246
    /**
247
     * Method that remove all data in the document root path
248
     */
249 1
    public static function clearDocumentRoot()
250
    {
251 1
        $rootDirs = array("css", "js", "media", "font");
252 1
        foreach ($rootDirs as $dir) {
253 1
            if (file_exists(WEB_DIR . DIRECTORY_SEPARATOR . $dir)) {
254
                try {
255 1
                    @shell_exec("rm -rf " . WEB_DIR . DIRECTORY_SEPARATOR . $dir);
256 1
                } catch (\Exception $e) {
257
                    Logger::log($e->getMessage());
258
                }
259 1
            }
260 1
        }
261 1
    }
262
263
    /**
264
     * Method that reloads config file
265
     */
266 2
    public function loadConfigData()
267
    {
268 2
        $this->config = Cache::getInstance()->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json",
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...
269 2
            Cache::JSON,
270 2
            TRUE) ?: [];
271 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
272 2
    }
273
274
    /**
275
     * Clear configuration set
276
     */
277 1
    public function clearConfig()
278
    {
279 1
        $this->config = [];
280 1
    }
281
282
    /**
283
     * Static wrapper for extracting params
284
     * @param string $key
285
     * @param mixed|null $defaultValue
286
     * @return mixed|null
287
     */
288 1
    public static function getParam($key, $defaultValue = null) {
289 1
        $param = Config::getInstance()->get($key);
290 1
        return (null !== $param) ? $param : $defaultValue;
291
    }
292
}
293