Passed
Push — main ( e2b3b9...324b47 )
by Rafael
46:15
created

Config::getDefaultMainFileInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
/* Copyright (C) 2024       Rafael San José         <[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
 * 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\Base;
20
21
use Exception;
22
use PDO;
23
use stdClass;
24
25
abstract class Config
26
{
27
    private const  AVAILABLE_GROUPS = ['main', 'db'];
28
29
    private static ?stdClass $config = null;
30
31
    public static function setDbConfig($values)
32
    {
33
        $data = (object)$values;
34
        if (!self::checkDatabaseConnection($data)) {
35
            return false;
36
        }
37
        self::saveConfig();
38
        return static::setConfig('db', $values);
39
    }
40
41
    private static function checkDatabaseConnection($data)
42
    {
43
        $dsn = "$data->type:host=$data->host;dbname=$data->name;charset=$data->charset";
44
        try {
45
            $options = [
46
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
47
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
48
                PDO::ATTR_EMULATE_PREPARES => false,
49
            ];
50
51
            $pdo = new PDO($dsn, $data->user, $data->pass, $options);
52
53
            // Ejecutar una simple consulta para verificar la conexión
54
            $pdo->query('SELECT 1');
55
56
            return true;
57
        } catch (Exception $e) {
58
            // Capturar errores y devolver false si la conexión falla
59
            return false;
60
        }
61
    }
62
63
    /**
64
     * Updates the configuration file with the information it has in memory.
65
     *
66
     * @return bool
67
     */
68
    public static function saveConfig(): bool
69
    {
70
        if (empty(self::$config)) {
71
            return true;
72
        }
73
        return file_put_contents(self::getConfigFilename(), json_encode(self::$config, JSON_PRETTY_PRINT)) !== false;
74
    }
75
76
    private static function setConfig(string $group, array $values): bool
77
    {
78
        if (empty($values)) {
79
            return true;
80
        }
81
82
        $group = trim(strtolower($group));
83
        if (!in_array($group, self::AVAILABLE_GROUPS)) {
84
            return false;
85
        }
86
87
        if (!isset(self::$config)) {
88
            self::$config = self::loadConfig();
89
            if (self::$config === null) {
90
                self::$config = new stdClass();
91
                self::$config->main = self::getDefaultMainFileInfo();
92
            }
93
        }
94
95
        $branch = self::$config->{$group} ?? new stdClass();
96
        foreach ($values as $key => $value) {
97
            $branch->{$key} = $value;
98
        }
99
100
        if (!empty($branch)) {
101
            self::$config->{$group} = $branch;
102
        }
103
104
        return static::saveConfig();
105
    }
106
107
    /**
108
     * Returns a stdClass with the program configuration.
109
     * If the configuration file does not exist, is not accessible, or is not correct, returns null.
110
     * The configuration is loaded from the file only once and stored in a variable. You can set $reload
111
     * to true to force a reload of the configuration file.
112
     *
113
     * @param bool $reload
114
     * @return stdClass
115
     */
116
    public static function loadConfig(bool $reload = false): ?stdClass
117
    {
118
        if (!$reload && isset(self::$config)) {
119
            return self::$config;
120
        }
121
122
        $filename = self::getConfigFilename();
123
        if (!file_exists($filename)) {
124
            return null;
125
        }
126
127
        $config = file_get_contents($filename);
128
        if ($config === false) {
129
            return self::$config;
130
        }
131
132
        $result = json_decode($config);
133
        if (json_last_error() === JSON_ERROR_NONE) {
134
            self::$config = $result;
135
        }
136
137
        return $result;
138
    }
139
140
    /**
141
     * Returns the config.json complete path.
142
     *
143
     * @return string
144
     */
145
    private static function getConfigFilename(): string
146
    {
147
        return realpath(BASE_PATH . '/..') . DIRECTORY_SEPARATOR . 'config.json';
148
    }
149
150
    private static function getDefaultMainFileInfo()
151
    {
152
        $result = new stdClass();
153
        $result->path = constant('BASE_PATH');
154
        $result->url = constant('BASE_URL');
155
        return $result;
156
    }
157
158
    public static function setMainConfig($values)
159
    {
160
        return static::setConfig('main', $values);
161
    }
162
}
163