Passed
Push — master ( 1dadf3...61c4e2 )
by Fran
03:43
created

Config::getTemplatePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
ccs 3
cts 3
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
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
    const CONFIG_FILE = 'config.json';
26
27
    protected $config = array();
28
    static public $defaults = array(
29
        "db_host" => "localhost",
30
        "db_port" => "3306",
31
        "default_language" => "es_ES",
32
        "debug" => true,
33
        "front.version" => "v1",
34
        "version" => "v1",
35
    );
36
    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...
37
    static public $encrypted = array('db_password');
38
    static public $optional = [
39
        'platform_name', // Platform name
40
        'restricted', // Restrict the web access
41
        'admin_login', // Enable web login for admin
42
        'logger.phpFire', // Enable phpFire to trace the logs in the browser
43
        'logger.memory', // Enable log memory usage un traces
44
        'poweredBy', // Show PoweredBy header customized
45
        'author', // Author for auto generated files
46
        'author_email', // Author email for auto generated files
47
        'version', // Platform version(for cache purposes)
48
        'front.version', // Static resources version
49
        'cors.enabled', // Enable CORS (regex with the domains, * for all)
50
        'pagination.limit', // Pagination limit for autogenerated api admin
51
        'api.secret', // Secret passphrase to securize the api
52
        'api.admin', // Enable de autogenerated api admin(wok)
53
        'log.level', // Max log level(default INFO)
54
        'admin_action', // Default admin url when access to /admin
55
        'cache.var', // Static cache var
56
        'twig.auto_reload', // Enable or disable auto reload templates for twig
57
        'modules.extend', // Variable for extending the current functionality
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 7
        }
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 1
                }
97 1
            }
98 1
        }
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 2
                }
116 2
            }
117 2
        }
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 2
                if (!array_key_exists($required, $this->config)) {
141 1
                    $configured = false;
142 1
                    break;
143
                }
144 1
            }
145 1
        }
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
            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...
174 2
            Config::getInstance()->loadConfigData();
175 2
            $saved = true;
176 2
        } catch (ConfigException $e) {
177
            Logger::log($e->getMessage(), LOG_ERR);
178
        }
179 2
        return $saved;
180
    }
181
182
    /**
183
     * Method that returns a config value
184
     * @param string $param
185
     * @param mixed $defaultValue
186
     *
187
     * @return mixed|null
188
     */
189 4
    public function get($param, $defaultValue = null)
190
    {
191 4
        return array_key_exists($param, $this->config) ? $this->config[$param] : $defaultValue;
192
    }
193
194
    /**
195
     * Method that returns all the configuration
196
     * @return array
197
     */
198 2
    public function dumpConfig()
199
    {
200 2
        return $this->config ?: [];
201
    }
202
203
    /**
204
     * Method that reloads config file
205
     */
206 2
    public function loadConfigData()
207
    {
208 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...
209 2
            Cache::JSON,
210 2
            TRUE) ?: [];
211 2
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
212 2
    }
213
214
    /**
215
     * Clear configuration set
216
     */
217 1
    public function clearConfig()
218
    {
219 1
        $this->config = [];
220 1
    }
221
222
    /**
223
     * Static wrapper for extracting params
224
     * @param string $key
225
     * @param mixed|null $defaultValue
226
     * @return mixed|null
227
     */
228 2
    public static function getParam($key, $defaultValue = null) {
229 2
        $param = Config::getInstance()->get($key);
230 2
        return (null !== $param) ? $param : $defaultValue;
231
    }
232
}
233