Passed
Push — main ( bd30b4...b6e144 )
by Rafael
11:59
created

Config::loadConfig()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 24
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A Config::connectToDatabaseAndAuth() 0 14 4
1
<?php
2
/**
3
 * Copyright (C) 2022-2023  Rafael San José Tovar   <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
namespace Alxarafe\Core\Singletons;
20
21
use Alxarafe\Core\Helpers\Auth;
22
use Alxarafe\Database\DB;
23
use Alxarafe\Database\Engine;
24
use Alxarafe\Database\SqlHelper;
25
use Exception;
26
use Symfony\Component\Yaml\Yaml;
27
28
class Config
29
{
30
    /**
31
     * Contains the full name of the configuration file or null
32
     *
33
     * @var string::null
34
     */
35
    private static string $configFilename;
36
37
    /**
38
     * Contains an array with the variables defined in the configuration file.
39
     * Use setVar to assign or getVar to access the variables of the array.
40
     *
41
     * @var array
42
     */
43
    private static array $global;
44
45
    /**
46
     * Contains the instance to the database engine (or null)
47
     *
48
     * @var Engine
49
     */
50
    public static Engine $dbEngine;
51
52
    /**
53
     * Database name.
54
     *
55
     * @var string
56
     */
57
    public static string $dbName;
58
59
    /**
60
     * Contains de database tablename prefix
61
     *
62
     * @var string
63
     */
64
    public static string $dbPrefix;
65
66
    /**
67
     * Contains the instance to the specific SQL engine helper (or null)
68
     *
69
     * @var sqlHelper
70
     */
71
    private static SqlHelper $sqlHelper;
72
73
    /**
74
     * It is a static instance of the Auth class that contains the data of the
75
     * currently identified user.
76
     *
77
     * @var Auth
78
     */
79
    private static Auth $user;
80
81
    /**
82
     * Contains the user's name or null
83
     *
84
     * @var string|null
85
     */
86
    private static ?string $username = null;
87
88
    private TemplateRender $render;
0 ignored issues
show
Bug introduced by
The type Alxarafe\Core\Singletons\TemplateRender was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
introduced by
The private property $render is not used, and could be removed.
Loading history...
89
    private DebugTool $debug;
0 ignored issues
show
introduced by
The private property $debug is not used, and could be removed.
Loading history...
Bug introduced by
The type Alxarafe\Core\Singletons\DebugTool was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
90
91
    public function __construct()
92
    {
93
        if (!isset(self::$global)) {
94
            self::$global = self::loadConfigurationFile();
95
            if (empty(self::$global)) {
96
                return false;
97
            }
98
        }
99
        self::defineConstants();
100
    }
101
102
    /**
103
     * Define todas las constantes de la sección 'constants' del archivo config.yaml
104
     * La sección constants contiene las constantes en grupos de tipo.
105
     * TODO: De momento se contempla boolean y el resto.
106
     *
107
     * @author  Rafael San José Tovar <[email protected]>
108
     * @version 2022.1218
109
     *
110
     */
111
    private static function defineConstants()
112
    {
113
        foreach (self::$global['constants'] ?? [] as $type => $types) {
114
            foreach ($types as $name => $value) {
115
                switch ($type) {
116
                    case 'boolean':
117
                        define($name, in_array(strtolower($value), ['1', 'true']));
118
                        break;
119
                    default:
120
                        define($name, $value);
121
                }
122
            }
123
        }
124
    }
125
126
    /**
127
     * @throws DebugBarException
128
     */
129
    public static function connectToDatabaseAndAuth(): bool
130
    {
131
        if (!self::connectToDataBase()) {
132
            FlashMessages::setError('Database Connection error...');
133
            return false;
134
        }
135
        if (!isset(self::$user)) {
136
            self::$user = new Auth();
137
            self::$username = self::$user->getUser();
138
            if (self::$username === null) {
139
                self::$user->login();
140
            }
141
        }
142
        return true;
143
    }
144
145
    /**
146
     * Returns an array with the configuration defined in the configuration file.
147
     * If the configuration file does not exist, take us to the application
148
     * configuration form to create it
149
     *
150
     * @return array
151
     */
152
    public static function loadConfigurationFile(): array
153
    {
154
        $filename = self::getConfigFileName();
155
        if (isset($filename) && file_exists($filename)) {
156
            $yaml = file_get_contents($filename);
157
            if ($yaml) {
158
                return YAML::parse($yaml);
159
            }
160
        }
161
        return [];
162
    }
163
164
    /**
165
     * Returns the name of the configuration file. By default, create the config
166
     * folder and enter the config.yaml file inside it.
167
     * If you want to use another folder for the configuration, you will have to
168
     * define it in the constant CONFIGURATION_DIR before invoking this method,
169
     * this folder must exist.
170
     *
171
     * @return string|null
172
     */
173
    public static function getConfigFileName(): ?string
174
    {
175
        if (isset(self::$configFilename)) {
176
            return self::$configFilename;
177
        }
178
        $filename = constant('CONFIGURATION_DIR') . 'config.yaml';
179
        if (
180
            file_exists($filename) || is_dir(constant('CONFIGURATION_DIR')) || mkdir(constant('CONFIGURATION_DIR'), 0777, true)) {
181
            self::$configFilename = $filename;
182
        }
183
        return self::$configFilename;
184
    }
185
186
    /**
187
     * Gets the contents of a variable. If the variable does not exist, return null.
188
     *
189
     * @param string $module
190
     * @param string $section
191
     * @param string $name
192
     *
193
     * @return string|null ?string
194
     */
195
    public static function getVar(string $module, string $section, string $name): ?string
196
    {
197
        return self::$global[$module][$section][$name] ?? null;
198
    }
199
200
    /**
201
     * If self::$dbEngine contain null, create an Engine instance with the
202
     * database connection and assigns it to self::$dbEngine.
203
     *
204
     * @param string $db
205
     *
206
     * @return bool
207
     * @throws DebugBarException
208
     */
209
    public static function connectToDatabase($db = 'main'): bool
210
    {
211
        if (isset(self::$dbEngine)) {
212
            return true;
213
        }
214
215
        Config::$dbPrefix = strtolower(self::$global['database'][$db]['dbPrefix'] ?? '');
216
        Config::$dbName = strtolower(self::$global['database'][$db]['dbName']);
217
218
        $dbEngineName = self::$global['database'][$db]['dbEngineName'] ?? 'PdoMySql';
219
        $helperName = 'Sql' . substr($dbEngineName, 3);
220
221
        Debug::sqlMessage("Using '$dbEngineName' engine.");
222
        Debug::sqlMessage("Using '$helperName' SQL helper engine.");
223
224
        $sqlEngine = '\\Alxarafe\\Database\\SqlHelpers\\' . $helperName;
225
        $engine = '\\Alxarafe\\Database\\Engines\\' . $dbEngineName;
226
        try {
227
            self::$sqlHelper = new $sqlEngine();
228
            self::$dbEngine = new $engine([
229
                'dbUser' => self::$global['database'][$db]['dbUser'],
230
                'dbPass' => self::$global['database'][$db]['dbPass'],
231
                'dbName' => self::$global['database'][$db]['dbName'],
232
                'dbHost' => self::$global['database'][$db]['dbHost'],
233
                'dbPort' => self::$global['database'][$db]['dbPort'],
234
            ]);
235
            new DB();
236
            return isset(self::$dbEngine) && self::$dbEngine->connect() && self::$dbEngine->checkConnection();
237
        } catch (Exception $e) {
238
            Debug::addException($e);
239
        }
240
        return false;
241
    }
242
243
    public static function getEngine(): Engine
244
    {
245
        return self::$dbEngine;
246
    }
247
248
    public static function getSqlHelper(): SqlHelper
249
    {
250
        return self::$sqlHelper;
251
    }
252
253
    /**
254
     * Return true y the config file exists
255
     *
256
     * @return bool
257
     */
258
    public static function configFileExists(): bool
259
    {
260
        return (file_exists(self::getConfigFileName()));
261
    }
262
263
    public static function getUsername()
264
    {
265
        return self::$username;
266
    }
267
268
    /**
269
     * Set the display settings.
270
     *
271
     * @return void
272
     */
273
    public function loadViewsConfig()
274
    {
275
        dump(debug_backtrace());
276
        die('loadViewsConfig');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
277
        Render::setSkin(self::getVar('templaterender', 'main', 'skin') ?? 'default');
0 ignored issues
show
Unused Code introduced by
Alxarafe\Core\Singletons..., 'skin') ?? 'default') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
278
        Render::setTemplate(self::getVar('templaterender', 'main', 'skin') ?? 'default');
279
    }
280
281
    /**
282
     * Stores all the variables in a permanent file so that they can be loaded
283
     * later with loadConfigFile()
284
     * Returns true if there is no error when saving the file.
285
     *
286
     * @return bool
287
     */
288
    public static function saveConfigFile(): bool
289
    {
290
        $configFile = self::getConfigFileName();
291
        if (!isset($configFile)) {
292
            return false;
293
        }
294
        return file_put_contents($configFile, YAML::dump(self::$global, 3)) !== false;
295
    }
296
297
    /**
298
     * Stores a variable.
299
     *
300
     * @param string $module
301
     * @param string $section
302
     * @param string $name
303
     * @param string $value
304
     */
305
    public static function setVar(string $module, string $section, string $name, string $value)
306
    {
307
        self::$global[$module][$section][$name] = $value;
308
    }
309
}
310