13
13
14
14
namespace CodeIgniter \Database ;
15
15
16
+ use CodeIgniter \Exceptions \ConfigException ;
17
+ use CodeIgniter \Exceptions \CriticalError ;
16
18
use 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,38 @@ 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
150
+ */
151
+ private function checkDbExtension (string $ driver ): bool
152
+ {
153
+ $ extensionMap = [
154
+ // DBDriver => PHP extension
155
+ 'MySQLi ' => 'mysqli ' ,
156
+ 'SQLite3 ' => 'sqlite3 ' ,
157
+ 'Postgre ' => 'pgsql ' ,
158
+ 'SQLSRV ' => 'sqlsrv ' ,
159
+ 'OCI8 ' => 'oci8 ' ,
160
+ ];
161
+
162
+ $ extension = $ extensionMap [$ driver ] ?? '' ;
163
+
164
+ if ($ extension === '' ) {
165
+ $ message = 'Invalid DBDriver name: " ' . $ driver . '" ' ;
166
+
167
+ throw new ConfigException ($ message );
168
+ }
169
+
170
+ if (extension_loaded ($ extension )) {
171
+ return true ;
172
+ }
173
+
174
+ $ message = 'The required PHP extension " ' . $ extension . '" is not loaded. '
175
+ . ' Install and enable it to use " ' . $ driver . '" driver. ' ;
176
+
177
+ throw new CriticalError ($ message );
178
+ }
141
179
}
0 commit comments