Passed
Push — master ( d2956c...9cde44 )
by Fran
03:15
created

Config::save()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 3
nop 2
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
ccs 9
cts 10
cp 0.9
crap 2.004
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
        'modules.extend', // Variable for extending the current functionality
56
    ];
57
    protected $debug = false;
58
59
    /**
60
     * Config Constructor
61
     */
62 8
    public function __construct()
63
    {
64 8
        $this->init();
65 8
    }
66
67
    /**
68
     * Method that load the configuration data into the system
69
     * @return Config
70
     */
71 8
    protected function init()
72
    {
73 8
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json")) {
74 7
            $this->loadConfigData();
75 7
        }
76 8
        return $this;
77
    }
78
79
    /**
80
     * Method that saves the configuration
81
     * @param array $data
82
     * @param array $extra
83
     * @return array
84
     */
85 2
    protected static function saveConfigParams(array $data, array $extra)
86
    {
87 2
        Logger::log('Saving required config parameters');
88
        //En caso de tener parámetros nuevos los guardamos
89 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
90 1
            foreach ($extra['label'] as $index => $field) {
91 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
92
                    /** @var $data array */
93 1
                    $data[$field] = $extra['value'][$index];
94 1
                }
95 1
            }
96 1
        }
97 2
        return $data;
98
    }
99
100
    /**
101
     * Method that saves the extra parameters into the configuration
102
     * @param array $data
103
     * @return array
104
     */
105 2
    protected static function saveExtraParams(array $data)
106
    {
107 2
        $final_data = array();
108 2
        if (count($data) > 0) {
109 2
            Logger::log('Saving extra configuration parameters');
110 2
            foreach ($data as $key => $value) {
111 2
                if (null !== $value || $value !== '') {
112 2
                    $final_data[$key] = $value;
113 2
                }
114 2
            }
115 2
        }
116 2
        return $final_data;
117
    }
118
119
    /**
120
     * Method that returns if the system is in debug mode
121
     * @return boolean
122
     */
123 6
    public function getDebugMode()
124
    {
125 6
        return $this->debug;
126
    }
127
128
    /**
129
     * Method that returns the cache path
130
     * @return string
131
     */
132 2
    public function getCachePath()
133
    {
134 2
        return CACHE_DIR;
135
    }
136
137
    /**
138
     * Method that returns the templates path
139
     * @return string
140
     */
141 2
    public function getTemplatePath()
142
    {
143 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...
144 2
        return realpath($path);
145
    }
146
147
    /**
148
     * Method that checks if the platform is proper configured
149
     * @return boolean
150
     */
151 2
    public function isConfigured()
152
    {
153 2
        Logger::log('Checking configuration');
154 2
        $configured = (count($this->config) > 0);
155 2
        if ($configured) {
156 1
            foreach (static::$required as $required) {
157 1
                if (!array_key_exists($required, $this->config)) {
158 1
                    $configured = false;
159 1
                    break;
160
                }
161 1
            }
162 1
        }
163 2
        return ($configured || $this->checkTryToSaveConfig());
164
    }
165
166
    /**
167
     * Method that check if the user is trying to save the config
168
     * @return bool
169
     */
170 2
    public function checkTryToSaveConfig()
171
    {
172 2
        $uri = Request::getInstance()->getRequestUri();
173 2
        $method = Request::getInstance()->getMethod();
174 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
175
    }
176
177
    /**
178
     * Method that saves all the configuration in the system
179
     *
180
     * @param array $data
181
     * @param array|null $extra
182
     * @return boolean
183
     */
184 2
    public static function save(array $data, array $extra = null)
185
    {
186 2
        $data = self::saveConfigParams($data, $extra);
187 2
        $final_data = self::saveExtraParams($data);
188 2
        $saved = false;
189
        try {
190 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...
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 4
    public function get($param, $defaultValue = null)
207
    {
208 4
        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 1
    {
217 2
        return $this->config ?: [];
218
    }
219
220
    /**
221
     * Method that returns the Propel ORM parameters to setup the models
222
     * @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...
223
     */
224 1
    public function getPropelParams()
225
    {
226 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...
227
    }
228
229
    /**
230
     * Method that creates any parametrized path
231
     * @param string $dir
232
     * throws ConfigException
233
     */
234 7
    public static function createDir($dir)
235
    {
236
        try {
237 7
            if (!is_dir($dir) && @mkdir($dir, 0775, true) === false) {
238
                throw new \Exception(_('Can\'t create directory ') . $dir);
239
            }
240 7
        } catch (\Exception $e) {
241
            Logger::log($e->getMessage(), LOG_WARNING);
242
            if (!file_exists(dirname($dir))) {
243
                throw new ConfigException($e->getMessage() . $dir);
244
            }
245
        }
246 7
    }
247
248
    /**
249
     * Method that remove all data in the document root path
250
     */
251 1
    public static function clearDocumentRoot()
252
    {
253 1
        $rootDirs = array("css", "js", "media", "font");
254 1
        foreach ($rootDirs as $dir) {
255 1
            if (file_exists(WEB_DIR . DIRECTORY_SEPARATOR . $dir)) {
256
                try {
257 1
                    @shell_exec("rm -rf " . WEB_DIR . DIRECTORY_SEPARATOR . $dir);
258 1
                } catch (\Exception $e) {
259
                    Logger::log($e->getMessage());
260
                }
261 1
            }
262 1
        }
263 1
    }
264
265
    /**
266
     * Method that reloads config file
267
     */
268 2
    public function loadConfigData()
269
    {
270 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...
271 2
            Cache::JSON,
272 2
            TRUE) ?: [];
273 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
274 2
    }
275
276
    /**
277
     * Clear configuration set
278
     */
279 1
    public function clearConfig()
280
    {
281 1
        $this->config = [];
282 1
    }
283
284
    /**
285
     * Static wrapper for extracting params
286
     * @param string $key
287
     * @param mixed|null $defaultValue
288
     * @return mixed|null
289
     */
290 2
    public static function getParam($key, $defaultValue = null) {
291 2
        $param = Config::getInstance()->get($key);
292 2
        return (null !== $param) ? $param : $defaultValue;
293
    }
294
}
295