Passed
Push — main ( db810f...4cd58e )
by Dimitri
12:03
created

Database::connect()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 31
rs 9.4555
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Config;
13
14
use BlitzPHP\Contracts\Database\ConnectionInterface;
15
use BlitzPHP\Database\Database as Db;
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Database\Database 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...
16
use BlitzPHP\Loader\Services;
17
use InvalidArgumentException;
18
19
/**
20
 * Configuration pour la base de données
21
 */
22
class Database
23
{
24
    /**
25
     * Cache pour les instances de toutes les connections
26
     * qui ont été requetées en tant que instance partagées
27
     *
28
     * @var array<string, ConnectionInterface>
29
     */
30
    protected static $instances = [];
31
32
    /**
33
     * L'instance principale utilisée pour gérer toutes les ouvertures à la base de données.
34
     *
35
     * @var Db|null
36
     */
37
    protected static $factory;
38
39
    /**
40
     * Recupere les informations a utiliser pour la connexion a la base de données
41
     *
42
     * @return array [group, configuration]
43
     */
44
    public static function connectionInfo(array|string|null $group = null): array
45
    {
46
        if (is_array($group)) {
47
            $config = $group;
48
            $group  = 'custom-' . md5(json_encode($config));
49
        }
50
51
        $config ??= config('database');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config does not seem to be defined for all execution paths leading up to this point.
Loading history...
52
53
        if (empty($group)) {
54
            $group = $config['connection'] ?? 'auto';
55
        }
56
        if ($group === 'auto') {
57
            $group = on_test() ? 'test' : (on_prod() ? 'production' : 'development');
58
        }
59
60
        if (! isset($config[$group]) && strpos($group, 'custom-') === false) {
61
            $group = 'default';
62
        }
63
64
        if (is_string($group) && ! isset($config[$group]) && strpos($group, 'custom-') !== 0) {
65
            throw new InvalidArgumentException($group . ' is not a valid database connection group.');
66
        }
67
68
        if (strpos($group, 'custom-') !== false) {
69
            $config = [$group => $config];
70
        }
71
72
        $config = $config[$group];
73
74
        if (str_contains($config['driver'], 'sqlite') && $config['database'] !== ':memory:' && ! str_contains($config['database'], DS)) {
75
            $config['database'] = APP_STORAGE_PATH . $config['database'];
76
        }
77
78
        return [$group, $config];
79
    }
80
81
    /**
82
     * Ouvre une connexion
83
     *
84
     * @param array|ConnectionInterface|string|null $group  Nom du groupe de connexion à utiliser, ou un tableau de paramètres de configuration.
85
     * @param bool                                  $shared Doit-on retourner une instance partagée
86
     */
87
    public static function connect($group = null, bool $shared = true): ConnectionInterface
88
    {
89
        // Si on a deja passer une connection, pas la peine de continuer
90
        if ($group instanceof ConnectionInterface) {
91
            return $group;
92
        }
93
94
        // Si le package "blitz-php/database" n'existe pas on renvoi une fake connection
95
        // Ceci est utile juste pour eviter le bug avec le service provider
96
        if (! class_exists(Db::class)) {
97
            return static::createMockConnection();
98
        }
99
100
        [$group, $config] = static::connectionInfo($group);
101
102
        if ($shared && isset(static::$instances[$group])) {
103
            return static::$instances[$group];
104
        }
105
106
        static::ensureFactory();
107
108
        $connection = static::$factory->load(
0 ignored issues
show
Bug introduced by
The method load() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
        /** @scrutinizer ignore-call */ 
109
        $connection = static::$factory->load(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
109
            $config,
110
            $group,
111
            Services::logger(),
112
            Services::event()
113
        );
114
115
        static::$instances[$group] = &$connection;
116
117
        return $connection;
118
    }
119
120
    /**
121
     * Renvoie un tableau contenant toute les connxions deja etablies.
122
     */
123
    public static function getConnections(): array
124
    {
125
        return static::$instances;
126
    }
127
128
    /**
129
     * Charge et retourne une instance du Creator specifique au groupe de la base de donnees
130
     * et charge le groupe s'il n'est pas encore chargé.
131
     *
132
     * @param array|ConnectionInterface|string|null $group
133
     *
134
     * @return \BlitzPHP\Database\Creator\BaseCreator
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Database\Creator\BaseCreator 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...
135
     */
136
    public static function creator($group = null, bool $shared = true)
137
    {
138
        $db = static::connect($group, $shared);
139
140
        return static::$factory->loadCreator($db);
141
    }
142
143
    /**
144
     * Retourne une nouvelle de la classe Database Utilities.
145
     *
146
     * @param array|string|null $group
147
     *
148
     * @return \Blitzphp\Database\BaseUtils
0 ignored issues
show
Bug introduced by
The type Blitzphp\Database\BaseUtils 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...
149
     */
150
    public static function utils($group = null)
151
    {
152
        $db = static::connect($group);
153
154
        return static::$factory->loadUtils($db);
155
    }
156
157
    /**
158
     * S'assure que le gestionnaire de la base de données est chargé et prêt à être utiliser.
159
     */
160
    protected static function ensureFactory()
161
    {
162
        if (static::$factory instanceof Db) {
163
            return;
164
        }
165
166
        static::$factory = new Db();
167
    }
168
169
    private static function createMockConnection(): ConnectionInterface
170
    {
171
        /* trigger_warning('
172
            Utilisation d\'une connexion à la base de données invalide.
173
            Veuillez installer le package `blitz-php/database`.
174
        '); */
175
176
        return new class () implements ConnectionInterface {
177
            public function initialize()
178
            {
179
            }
180
181
            public function connect(bool $persistent = false)
182
            {
183
            }
184
185
            public function persistentConnect()
186
            {
187
            }
188
189
            public function reconnect()
190
            {
191
            }
192
193
            public function getConnection(?string $alias = null)
194
            {
195
            }
196
197
            public function setDatabase(string $databaseName)
198
            {
199
            }
200
201
            public function getDatabase(): string
202
            {
203
                return '';
204
            }
205
206
            public function error(): array
207
            {
208
                return [];
209
            }
210
211
            public function getPlatform(): string
212
            {
213
                return '';
214
            }
215
216
            public function getVersion(): string
217
            {
218
                return '';
219
            }
220
221
            public function query(string $sql, $binds = null)
222
            {
223
            }
224
225
            public function simpleQuery(string $sql)
226
            {
227
            }
228
229
            public function table($tableName)
230
            {
231
            }
232
233
            public function getLastQuery()
234
            {
235
            }
236
237
            public function escape($str)
238
            {
239
            }
240
241
            public function callFunction(string $functionName, ...$params)
242
            {
243
            }
244
245
            public function isWriteType($sql): bool
246
            {
247
                return false;
248
            }
249
        };
250
    }
251
}
252