13
13
14
14
namespace CodeIgniter \Database ;
15
15
16
+ use CodeIgniter \Exceptions \ConfigException ;
17
+ use CodeIgniter \Exceptions \CriticalError ;
16
18
use CodeIgniter \Exceptions \InvalidArgumentException ;
17
19
18
20
/**
@@ -54,6 +56,8 @@ public function load(array $params = [], string $alias = '')
54
56
throw new InvalidArgumentException ('You have not selected a database type to connect to. ' );
55
57
}
56
58
59
+ assert ($ this ->checkDbExtension ($ params ['DBDriver ' ]));
60
+
57
61
$ this ->connections [$ alias ] = $ this ->initDriver ($ params ['DBDriver ' ], 'Connection ' , $ params );
58
62
59
63
return $ this ->connections [$ alias ];
@@ -124,9 +128,9 @@ protected function parseDSN(array $params): array
124
128
/**
125
129
* Creates a database object.
126
130
*
127
- * @param string $driver Driver name. FQCN can be used.
128
- * @param string $class 'Connection'|'Forge'|'Utils'
129
- * @param array|object $argument The constructor parameter.
131
+ * @param string $driver Driver name. FQCN can be used.
132
+ * @param string $class 'Connection'|'Forge'|'Utils'
133
+ * @param array|ConnectionInterface $argument The constructor parameter or DB connection
130
134
*
131
135
* @return BaseConnection|BaseUtils|Forge
132
136
*/
@@ -138,4 +142,43 @@ protected function initDriver(string $driver, string $class, $argument): object
138
142
139
143
return new $ classname ($ argument );
140
144
}
145
+
146
+ /**
147
+ * Check the PHP database extension is loaded.
148
+ *
149
+ * @param string $driver DB driver or FQCN for custom driver
150
+ */
151
+ private function checkDbExtension (string $ driver ): bool
152
+ {
153
+ if (str_contains ($ driver , '\\' )) {
154
+ // Cannot check a fully qualified classname for a custom driver.
155
+ return true ;
156
+ }
157
+
158
+ $ extensionMap = [
159
+ // DBDriver => PHP extension
160
+ 'MySQLi ' => 'mysqli ' ,
161
+ 'SQLite3 ' => 'sqlite3 ' ,
162
+ 'Postgre ' => 'pgsql ' ,
163
+ 'SQLSRV ' => 'sqlsrv ' ,
164
+ 'OCI8 ' => 'oci8 ' ,
165
+ ];
166
+
167
+ $ extension = $ extensionMap [$ driver ] ?? '' ;
168
+
169
+ if ($ extension === '' ) {
170
+ $ message = 'Invalid DBDriver name: " ' . $ driver . '" ' ;
171
+
172
+ throw new ConfigException ($ message );
173
+ }
174
+
175
+ if (extension_loaded ($ extension )) {
176
+ return true ;
177
+ }
178
+
179
+ $ message = 'The required PHP extension " ' . $ extension . '" is not loaded. '
180
+ . ' Install and enable it to use " ' . $ driver . '" driver. ' ;
181
+
182
+ throw new CriticalError ($ message );
183
+ }
141
184
}
0 commit comments