Completed
Push — master ( 8fedda...c65989 )
by Fran
03:24
created

Config::checkTryToSaveConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
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
    protected $config = array();
25
    static public $defaults = array(
26
        "db_host" => "localhost",
27
        "db_port" => "3306",
28
        "default_language" => "es_ES",
29
    );
30
    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...
31
    static public $encrypted = array('db_password');
32
    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');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 243 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...
33
    protected $debug = false;
34
35
    /**
36
     * Config Constructor
37
     */
38 8
    public function __construct() {
39 8
        $this->init();
40 8
    }
41
42
    /**
43
     * Método que carga la configuración del sistema
44
     * @return Config
45
     */
46 8
    protected function init() {
47 8
        if (file_exists(CONFIG_DIR.DIRECTORY_SEPARATOR."config.json"))
48 8
        {
49 7
            $this->loadConfigData();
50 7
        } else {
51 1
            $this->debug = true;
52
        }
53 8
        return $this;
54
    }
55
56
    /**
57
     * Método que guarda los datos de la configuración
58
     * @param array $data
59
     * @param array $extra
60
     * @return array
61
     */
62 2
    protected static function saveConfigParams(array $data, array $extra) {
63
        //En caso de tener parámetros nuevos los guardamos
64 2
        if (!empty($extra['label'])) {
65 1
            foreach ($extra['label'] as $index => $field) {
66 1
                if (array_key_exists($index, $extra['value']) && !empty($extra['value'][$index])) {
67
                    /** @var $data array */
68 1
                    $data[$field] = $extra['value'][$index];
69 1
                }
70 1
            }
71 1
        }
72 2
        return $data;
73
    }
74
75
    /**
76
     * Método que guarda los parámetros adicionales de la configuración
77
     * @param array $data
78
     * @return array
79
     */
80 2
    protected static function saveExtraParams(array $data) {
81 2
        $final_data = array();
82 2
        if (count($data) > 0) {
83 2
            foreach ($data as $key => $value) {
84 2
                if (null !== $value || $value !== '') {
85 2
                    $final_data[$key] = $value;
86 2
                }
87 2
            }
88 2
        }
89 2
        return $final_data;
90
    }
91
92
    /**
93
     * Método que devuelve si la plataforma está en modo debug
94
     * @return boolean
95
     */
96
    public function getDebugMode() { return $this->debug; }
97
98
    /**
99
     * Método que devuelve el path de cache
100
     * @return string
101
     */
102
    public function getCachePath() { return CACHE_DIR; }
103
104
    /**
105
     * Método que devuelve el path general de templates de PSFS
106
     * @return string
107
     */
108 2
    public function getTemplatePath() {
109 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 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...
110 2
        return realpath($path);
111
    }
112
113
    /**
114
     * Método que indica si se ha configurado correctamente la plataforma
115
     * @return boolean
116
     */
117 3
    public function isConfigured()
118
    {
119 3
        $configured = (count($this->config) > 0);
120 3
        if ($configured) {
121
            foreach (static::$required as $required) {
122
                if (!array_key_exists($required, $this->config)) {
123
                    $configured = false;
124
                    break;
125
                }
126
            }
127
        }
128 3
        return ($configured || $this->checkTryToSaveConfig());
129
    }
130
131
    /**
132
     * Method that check if the user is trying to save the config
133
     * @return bool
134
     */
135 3
    public function checkTryToSaveConfig()
136
    {
137 3
        $uri = Request::getInstance()->getRequestUri();
138 3
        $method = Request::getInstance()->getMethod();
139 3
        return (preg_match('/^\/admin\/(config|setup)$/', $uri) !== false && strtoupper($method) === 'POST');
140
    }
141
142
    /**
143
     * Método que guarda la configuración del framework
144
     *
145
     * @param array $data
146
     * @param array|null $extra
147
     * @return boolean
148
     */
149 2
    public static function save(array $data, array $extra = null) {
150 2
        $data = self::saveConfigParams($data, $extra);
151 2
        $final_data = self::saveExtraParams($data);
152 2
        $saved = false;
153
        try {
154 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 122 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...
155 2
            $saved = true;
156 2
        }catch (ConfigException $e) {
157
            Logger::getInstance()->errorLog($e->getMessage());
158
        }
159 2
        return $saved;
160
    }
161
162
    /**
163
     * Método que devuelve un parámetro de configuración
164
     * @param string $param
165
     *
166
     * @return mixed|null
167
     */
168 2
    public function get($param) {
169 2
        return array_key_exists($param, $this->config) ? $this->config[$param] : null;
170
    }
171
172
    /**
173
     * Método que devuelve toda la configuración en un array
174
     * @return array|null
175
     */
176 2
    public function dumpConfig() {
177 2
        return $this->config;
178
    }
179
180
    /**
181
     * Servicio que devuelve los parámetros de configuración de Propel para las BD
182
     * @return array|null
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string? 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...
183
     */
184
    public function getPropelParams() {
185
        return Cache::getInstance()->getDataFromFile(__DIR__.DIRECTORY_SEPARATOR.'properties.json', Cache::JSON, true);
186
    }
187
188
    /**
189
     * Método estático para la generación de directorios
190
     * @param string $dir
191
     * throws ConfigException
192
     */
193 4
    public static function createDir($dir) {
194
        try {
195 4
            if (@mkdir($dir, 0775, true) === false) {
196 1
                throw new \Exception(_('Can\'t create directory ').$dir);
197
            }
198 4
        }catch (\Exception $e) {
199 3
            if (!file_exists(dirname($dir))) {
200
                throw new ConfigException($e->getMessage().$dir);
201
            }
202
        }
203 4
    }
204
205
    /**
206
     * Método estático que elimina los directorio del document root
207
     */
208 1
    public static function clearDocumentRoot() {
209 1
        $rootDirs = array("css", "js", "media", "font");
210 1
        foreach ($rootDirs as $dir) {
211 1
            if (file_exists(WEB_DIR.DIRECTORY_SEPARATOR.$dir)) {
212
                try {
213 1
                    @shell_exec("rm -rf ".WEB_DIR.DIRECTORY_SEPARATOR.$dir);
214 1
                } catch(\Exception $e) {
215
                    Logger::getInstance()->errorLog($e->getMessage());
216 1
                }
217 1
            }
218 1
        }
219 1
    }
220
221
    /**
222
     * Method that reloads config file
223
     */
224 1
    public function loadConfigData()
225
    {
226 1
        $this->config = Cache::getInstance()->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json", Cache::JSON, TRUE) ?: array();
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...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 142 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 1
        $this->debug = (array_key_exists('debug', $this->config)) ? (bool)$this->config['debug'] : FALSE;
228 1
    }
229
}
230