Passed
Push — master ( 71a986...d378fe )
by Fran
04:06
created

Config   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 243
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 93.62%

Importance

Changes 0
Metric Value
dl 0
loc 243
ccs 88
cts 94
cp 0.9362
rs 8.3396
c 0
b 0
f 0
wmc 44
lcom 1
cbo 5

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A init() 0 7 2
B saveConfigParams() 0 14 6
B saveExtraParams() 0 13 5
A getDebugMode() 0 4 1
A getCachePath() 0 4 1
A getTemplatePath() 0 5 1
B isConfigured() 0 14 5
A checkTryToSaveConfig() 0 6 2
A save() 0 14 2
A get() 0 4 2
A dumpConfig() 0 4 2
A getPropelParams() 0 4 1
B createDir() 0 13 5
A clearDocumentRoot() 0 13 4
A loadConfigData() 0 7 3
A clearConfig() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like Config often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Config, and based on these observations, apply Extract Interface, too.

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
    );
31
    static public $required = array('db_host', 'db_port', 'db_name', 'db_user', 'db_password', 'home_action', 'default_language');
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...
32
    static public $encrypted = array('db_password');
33
    static public $optional = array('platform_name', 'debug', 'restricted', 'admin_login', 'logger.phpFire', 'logger.memory', 'poweredBy', 'author', 'author_email', 'version', 'front.version', 'cors.enabled', 'pagination.limit', 'api.secret', 'api.admin', 'log.level', 'admin_action');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 285 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
    protected $debug = false;
35
36
    /**
37
     * Config Constructor
38
     */
39 8
    public function __construct()
40
    {
41 8
        $this->init();
42 8
    }
43
44
    /**
45
     * Method that load the configuration data into the system
46
     * @return Config
47
     */
48 8
    protected function init()
49
    {
50 8
        if (file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json")) {
51 7
            $this->loadConfigData();
52 7
        }
53 8
        return $this;
54
    }
55
56
    /**
57
     * Method that saves the configuration
58
     * @param array $data
59
     * @param array $extra
60
     * @return array
61
     */
62 2
    protected static function saveConfigParams(array $data, array $extra)
63
    {
64 2
        Logger::log('Saving required config parameters');
65
        //En caso de tener parámetros nuevos los guardamos
66 2
        if (array_key_exists('label', $extra) && is_array($extra['label'])) {
67 1
            foreach ($extra['label'] as $index => $field) {
68 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
69
                    /** @var $data array */
70 1
                    $data[$field] = $extra['value'][$index];
71 1
                }
72 1
            }
73 1
        }
74 2
        return $data;
75
    }
76
77
    /**
78
     * Method that saves the extra parameters into the configuration
79
     * @param array $data
80
     * @return array
81
     */
82 2
    protected static function saveExtraParams(array $data)
83
    {
84 2
        $final_data = array();
85 2
        if (count($data) > 0) {
86 2
            Logger::log('Saving extra configuration parameters');
87 2
            foreach ($data as $key => $value) {
88 2
                if (null !== $value || $value !== '') {
89 2
                    $final_data[$key] = $value;
90 2
                }
91 2
            }
92 2
        }
93 2
        return $final_data;
94
    }
95
96
    /**
97
     * Method that returns if the system is in debug mode
98
     * @return boolean
99
     */
100 6
    public function getDebugMode()
101
    {
102 6
        return $this->debug;
103
    }
104
105
    /**
106
     * Method that returns the cache path
107
     * @return string
108
     */
109 2
    public function getCachePath()
110
    {
111 2
        return CACHE_DIR;
112
    }
113
114
    /**
115
     * Method that returns the templates path
116
     * @return string
117
     */
118 2
    public function getTemplatePath()
119
    {
120 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...
121 2
        return realpath($path);
122
    }
123
124
    /**
125
     * Method that checks if the platform is proper configured
126
     * @return boolean
127
     */
128 2
    public function isConfigured()
129
    {
130 2
        Logger::log('Checking configuration');
131 2
        $configured = (count($this->config) > 0);
132 2
        if ($configured) {
133 1
            foreach (static::$required as $required) {
134 1
                if (!array_key_exists($required, $this->config)) {
135 1
                    $configured = false;
136 1
                    break;
137
                }
138 1
            }
139 1
        }
140 2
        return ($configured || $this->checkTryToSaveConfig());
141
    }
142
143
    /**
144
     * Method that check if the user is trying to save the config
145
     * @return bool
146
     */
147 2
    public function checkTryToSaveConfig()
148
    {
149 2
        $uri = Request::getInstance()->getRequestUri();
150 2
        $method = Request::getInstance()->getMethod();
151 2
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
152
    }
153
154
    /**
155
     * Method that saves all the configuration in the system
156
     *
157
     * @param array $data
158
     * @param array|null $extra
159
     * @return boolean
160
     */
161 2
    public static function save(array $data, array $extra = null)
162
    {
163 2
        $data = self::saveConfigParams($data, $extra);
164 2
        $final_data = self::saveExtraParams($data);
165 2
        $saved = false;
166
        try {
167 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...
168 2
            Config::getInstance()->loadConfigData();
169 2
            $saved = true;
170 2
        } catch (ConfigException $e) {
171
            Logger::log($e->getMessage(), LOG_ERR);
172
        }
173 2
        return $saved;
174
    }
175
176
    /**
177
     * Method that returns a config value
178
     * @param string $param
179
     *
180
     * @return mixed|null
181
     */
182 3
    public function get($param)
183
    {
184 3
        return array_key_exists($param, $this->config) ? $this->config[$param] : null;
185
    }
186
187
    /**
188
     * Method that returns all the configuration
189
     * @return array
190
     */
191 2
    public function dumpConfig()
192
    {
193 2
        return $this->config ?: [];
194
    }
195
196
    /**
197
     * Method that returns the Propel ORM parameters to setup the models
198
     * @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...
199
     */
200 1
    public function getPropelParams()
201
    {
202 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...
203
    }
204
205
    /**
206
     * Method that creates any parametrized path
207
     * @param string $dir
208
     * throws ConfigException
209
     */
210 8
    public static function createDir($dir)
211
    {
212
        try {
213 7
            if (!is_dir($dir) && @mkdir($dir, 0775, true) === false) {
214
                throw new \Exception(_('Can\'t create directory ') . $dir);
215
            }
216 8
        } catch (\Exception $e) {
217
            Logger::log($e->getMessage(), LOG_WARNING);
218
            if (!file_exists(dirname($dir))) {
219
                throw new ConfigException($e->getMessage() . $dir);
220
            }
221
        }
222 7
    }
223
224
    /**
225
     * Method that remove all data in the document root path
226
     */
227 1
    public static function clearDocumentRoot()
228
    {
229 1
        $rootDirs = array("css", "js", "media", "font");
230 1
        foreach ($rootDirs as $dir) {
231 1
            if (file_exists(WEB_DIR . DIRECTORY_SEPARATOR . $dir)) {
232
                try {
233 1
                    @shell_exec("rm -rf " . WEB_DIR . DIRECTORY_SEPARATOR . $dir);
234 1
                } catch (\Exception $e) {
235
                    Logger::log($e->getMessage());
236
                }
237 1
            }
238 1
        }
239 1
    }
240
241
    /**
242
     * Method that reloads config file
243
     */
244 2
    public function loadConfigData()
245
    {
246 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...
247 2
            Cache::JSON,
248 2
            TRUE) ?: [];
249 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
250 2
    }
251
252
    /**
253
     * Clear configuration set
254
     */
255 1
    public function clearConfig()
256
    {
257 1
        $this->config = [];
258 1
    }
259
}
260