DriverManager::getConnection()   B
last analyzed

Complexity

Conditions 8
Paths 48

Size

Total Lines 43
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 43
ccs 20
cts 20
cp 1
rs 8.4444
c 0
b 0
f 0
cc 8
nc 48
nop 3
crap 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL;
6
7
use Doctrine\Common\EventManager;
8
use Doctrine\DBAL\Driver\IBMDB2\DB2Driver;
9
use Doctrine\DBAL\Driver\Mysqli\Driver as MySQLiDriver;
10
use Doctrine\DBAL\Driver\OCI8\Driver as OCI8Driver;
11
use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySQLDriver;
12
use Doctrine\DBAL\Driver\PDOOracle\Driver as PDOOCIDriver;
13
use Doctrine\DBAL\Driver\PDOPgSql\Driver as PDOPgSQLDriver;
14
use Doctrine\DBAL\Driver\PDOSqlite\Driver as PDOSQLiteDriver;
15
use Doctrine\DBAL\Driver\PDOSqlsrv\Driver as PDOSQLSrvDriver;
16
use Doctrine\DBAL\Driver\SQLAnywhere\Driver as SQLAnywhereDriver;
17
use Doctrine\DBAL\Driver\SQLSrv\Driver as SQLSrvDriver;
18
use Doctrine\DBAL\Exception\DriverRequired;
19
use Doctrine\DBAL\Exception\InvalidDriverClass;
20
use Doctrine\DBAL\Exception\InvalidWrapperClass;
21
use Doctrine\DBAL\Exception\UnknownDriver;
22
use function array_keys;
23
use function array_map;
24
use function array_merge;
25
use function assert;
26
use function class_implements;
27
use function in_array;
28
use function is_string;
29
use function is_subclass_of;
30
use function parse_str;
31
use function parse_url;
32
use function preg_replace;
33
use function str_replace;
34
use function strpos;
35
use function substr;
36
37
/**
38
 * Factory for creating Doctrine\DBAL\Connection instances.
39
 */
40
final class DriverManager
41
{
42
    /**
43
     * List of supported drivers and their mappings to the driver classes.
44
     *
45
     * To add your own driver use the 'driverClass' parameter to
46
     * {@link DriverManager::getConnection()}.
47
     *
48
     * @var string[]
49
     */
50
    private static $_driverMap = [
51
        'pdo_mysql'   => PDOMySQLDriver::class,
52
        'pdo_sqlite'  => PDOSQLiteDriver::class,
53
        'pdo_pgsql'   => PDOPgSQLDriver::class,
54
        'pdo_oci'     => PDOOCIDriver::class,
55
        'oci8'        => OCI8Driver::class,
56
        'ibm_db2'     => DB2Driver::class,
57
        'pdo_sqlsrv'  => PDOSQLSrvDriver::class,
58
        'mysqli'      => MySQLiDriver::class,
59
        'sqlanywhere' => SQLAnywhereDriver::class,
60
        'sqlsrv'      => SQLSrvDriver::class,
61
    ];
62
63
    /**
64
     * List of URL schemes from a database URL and their mappings to driver.
65
     *
66
     * @var string[]
67
     */
68
    private static $driverSchemeAliases = [
69
        'db2'        => 'ibm_db2',
70
        'mssql'      => 'pdo_sqlsrv',
71
        'mysql'      => 'pdo_mysql',
72
        'mysql2'     => 'pdo_mysql', // Amazon RDS, for some weird reason
73
        'postgres'   => 'pdo_pgsql',
74
        'postgresql' => 'pdo_pgsql',
75
        'pgsql'      => 'pdo_pgsql',
76
        'sqlite'     => 'pdo_sqlite',
77
        'sqlite3'    => 'pdo_sqlite',
78
    ];
79
80
    /**
81
     * Private constructor. This class cannot be instantiated.
82
     */
83
    private function __construct()
84
    {
85
    }
86
87
    /**
88
     * Creates a connection object based on the specified parameters.
89
     * This method returns a Doctrine\DBAL\Connection which wraps the underlying
90
     * driver connection.
91
     *
92
     * $params must contain at least one of the following.
93
     *
94
     * Either 'driver' with one of the array keys of {@link $_driverMap},
95
     * OR 'driverClass' that contains the full class name (with namespace) of the
96
     * driver class to instantiate.
97
     *
98
     * Other (optional) parameters:
99
     *
100
     * <b>user (string)</b>:
101
     * The username to use when connecting.
102
     *
103
     * <b>password (string)</b>:
104
     * The password to use when connecting.
105
     *
106
     * <b>driverOptions (array)</b>:
107
     * Any additional driver-specific options for the driver. These are just passed
108
     * through to the driver.
109
     *
110
     * <b>pdo</b>:
111
     * You can pass an existing PDO instance through this parameter. The PDO
112
     * instance will be wrapped in a Doctrine\DBAL\Connection.
113
     *
114
     * <b>wrapperClass</b>:
115
     * You may specify a custom wrapper class through the 'wrapperClass'
116
     * parameter but this class MUST inherit from Doctrine\DBAL\Connection.
117
     *
118
     * <b>driverClass</b>:
119
     * The driver class to use.
120
     *
121
     * @param mixed[]            $params       The parameters.
122
     * @param Configuration|null $config       The configuration to use.
123
     * @param EventManager|null  $eventManager The event manager to use.
124
     *
125
     * @throws DBALException
126
     */
127 2337
    public static function getConnection(
128
        array $params,
129
        ?Configuration $config = null,
130
        ?EventManager $eventManager = null
131
    ) : Connection {
132
        // create default config and event manager, if not set
133 2337
        if ($config === null) {
134 2175
            $config = new Configuration();
135
        }
136
137 2337
        if ($eventManager === null) {
138 2175
            $eventManager = new EventManager();
139
        }
140
141 2337
        $params = self::parseDatabaseUrl($params);
142
143
        // URL support for MasterSlaveConnection
144 2293
        if (isset($params['master'])) {
145 130
            $params['master'] = self::parseDatabaseUrl($params['master']);
146
        }
147
148 2293
        if (isset($params['slaves'])) {
149 130
            foreach ($params['slaves'] as $key => $slaveParams) {
150 130
                $params['slaves'][$key] = self::parseDatabaseUrl($slaveParams);
151
            }
152
        }
153
154 2293
        self::_checkParams($params);
155
156 2227
        $className = $params['driverClass'] ?? self::$_driverMap[$params['driver']];
157
158 2227
        $driver = new $className();
159
160 2227
        $wrapperClass = Connection::class;
161 2227
        if (isset($params['wrapperClass'])) {
162 284
            if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
163 22
                throw InvalidWrapperClass::new($params['wrapperClass']);
164
            }
165
166 262
            $wrapperClass = $params['wrapperClass'];
167
        }
168
169 2205
        return new $wrapperClass($params, $driver, $config, $eventManager);
170
    }
171
172
    /**
173
     * Returns the list of supported drivers.
174
     *
175
     * @return string[]
176
     */
177
    public static function getAvailableDrivers() : array
178
    {
179
        return array_keys(self::$_driverMap);
180
    }
181
182
    /**
183
     * Checks the list of parameters.
184
     *
185
     * @param mixed[] $params The list of parameters.
186
     *
187
     * @throws DBALException
188
     */
189 2293
    private static function _checkParams(array $params) : void
190
    {
191
        // check existence of mandatory parameters
192
193
        // driver
194 2293
        if (! isset($params['driver']) && ! isset($params['driverClass'])) {
195 22
            throw DriverRequired::new();
196
        }
197
198
        // check validity of parameters
199
200
        // driver
201 2271
        if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
202 22
            throw UnknownDriver::new($params['driver'], array_keys(self::$_driverMap));
203
        }
204
205 2249
        if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass']), true)) {
206 22
            throw InvalidDriverClass::new($params['driverClass']);
207
        }
208 2227
    }
209
210
    /**
211
     * Normalizes the given connection URL path.
212
     *
213
     * @return string The normalized connection URL path
214
     */
215 550
    private static function normalizeDatabaseUrlPath(string $urlPath) : string
216
    {
217
        // Trim leading slash from URL path.
218 550
        return substr($urlPath, 1);
219
    }
220
221
    /**
222
     * Extracts parts from a database URL, if present, and returns an
223
     * updated list of parameters.
224
     *
225
     * @param mixed[] $params The list of parameters.
226
     *
227
     * @return mixed[] A modified list of parameters with info from a database
228
     *                 URL extracted into indidivual parameter parts.
229
     *
230
     * @throws DBALException
231
     */
232 2337
    private static function parseDatabaseUrl(array $params) : array
233
    {
234 2337
        if (! isset($params['url'])) {
235 1765
            return $params;
236
        }
237
238
        // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
239 594
        $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
240 594
        assert(is_string($url));
241
242 594
        $url = parse_url($url);
243
244 594
        if ($url === false) {
245
            throw new DBALException('Malformed parameter "url".');
246
        }
247
248 594
        $url = array_map('rawurldecode', $url);
249
250 594
        $params = self::parseDatabaseUrlScheme($url, $params);
251
252 550
        if (isset($url['host'])) {
253 484
            $params['host'] = $url['host'];
254
        }
255
256 550
        if (isset($url['port'])) {
257 44
            $params['port'] = $url['port'];
258
        }
259
260 550
        if (isset($url['user'])) {
261 352
            $params['user'] = $url['user'];
262
        }
263
264 550
        if (isset($url['pass'])) {
265 352
            $params['password'] = $url['pass'];
266
        }
267
268 550
        $params = self::parseDatabaseUrlPath($url, $params);
269 550
        $params = self::parseDatabaseUrlQuery($url, $params);
270
271 550
        return $params;
272
    }
273
274
    /**
275
     * Parses the given connection URL and resolves the given connection parameters.
276
     *
277
     * Assumes that the connection URL scheme is already parsed and resolved into the given connection parameters
278
     * via {@link parseDatabaseUrlScheme}.
279
     *
280
     * @see parseDatabaseUrlScheme
281
     *
282
     * @param mixed[] $url    The URL parts to evaluate.
283
     * @param mixed[] $params The connection parameters to resolve.
284
     *
285
     * @return mixed[] The resolved connection parameters.
286
     */
287 550
    private static function parseDatabaseUrlPath(array $url, array $params) : array
288
    {
289 550
        if (! isset($url['path'])) {
290
            return $params;
291
        }
292
293 550
        $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
294
295
        // If we do not have a known DBAL driver, we do not know any connection URL path semantics to evaluate
296
        // and therefore treat the path as regular DBAL connection URL path.
297 550
        if (! isset($params['driver'])) {
298 22
            return self::parseRegularDatabaseUrlPath($url, $params);
299
        }
300
301 528
        if (strpos($params['driver'], 'sqlite') !== false) {
302 198
            return self::parseSqliteDatabaseUrlPath($url, $params);
303
        }
304
305 330
        return self::parseRegularDatabaseUrlPath($url, $params);
306
    }
307
308
    /**
309
     * Parses the query part of the given connection URL and resolves the given connection parameters.
310
     *
311
     * @param mixed[] $url    The connection URL parts to evaluate.
312
     * @param mixed[] $params The connection parameters to resolve.
313
     *
314
     * @return mixed[] The resolved connection parameters.
315
     */
316 550
    private static function parseDatabaseUrlQuery(array $url, array $params) : array
317
    {
318 550
        if (! isset($url['query'])) {
319 528
            return $params;
320
        }
321
322 22
        $query = [];
323
324 22
        parse_str($url['query'], $query); // simply ingest query as extra params, e.g. charset or sslmode
325
326 22
        return array_merge($params, $query); // parse_str wipes existing array elements
327
    }
328
329
    /**
330
     * Parses the given regular connection URL and resolves the given connection parameters.
331
     *
332
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
333
     *
334
     * @see normalizeDatabaseUrlPath
335
     *
336
     * @param mixed[] $url    The regular connection URL parts to evaluate.
337
     * @param mixed[] $params The connection parameters to resolve.
338
     *
339
     * @return mixed[] The resolved connection parameters.
340
     */
341 352
    private static function parseRegularDatabaseUrlPath(array $url, array $params) : array
342
    {
343 352
        $params['dbname'] = $url['path'];
344
345 352
        return $params;
346
    }
347
348
    /**
349
     * Parses the given SQLite connection URL and resolves the given connection parameters.
350
     *
351
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
352
     *
353
     * @see normalizeDatabaseUrlPath
354
     *
355
     * @param mixed[] $url    The SQLite connection URL parts to evaluate.
356
     * @param mixed[] $params The connection parameters to resolve.
357
     *
358
     * @return mixed[] The resolved connection parameters.
359
     */
360 198
    private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array
361
    {
362 198
        if ($url['path'] === ':memory:') {
363 44
            $params['memory'] = true;
364
365 44
            return $params;
366
        }
367
368 154
        $params['path'] = $url['path']; // pdo_sqlite driver uses 'path' instead of 'dbname' key
369
370 154
        return $params;
371
    }
372
373
    /**
374
     * Parses the scheme part from given connection URL and resolves the given connection parameters.
375
     *
376
     * @param mixed[] $url    The connection URL parts to evaluate.
377
     * @param mixed[] $params The connection parameters to resolve.
378
     *
379
     * @return mixed[] The resolved connection parameters.
380
     *
381
     * @throws DBALException If parsing failed or resolution is not possible.
382
     */
383 594
    private static function parseDatabaseUrlScheme(array $url, array $params) : array
384
    {
385 594
        if (isset($url['scheme'])) {
386
            // The requested driver from the URL scheme takes precedence
387
            // over the default custom driver from the connection parameters (if any).
388 484
            unset($params['driverClass']);
389
390
            // URL schemes must not contain underscores, but dashes are ok
391 484
            $driver = str_replace('-', '_', $url['scheme']);
392 484
            assert(is_string($driver));
393
394
            // The requested driver from the URL scheme takes precedence over the
395
            // default driver from the connection parameters. If the driver is
396
            // an alias (e.g. "postgres"), map it to the actual name ("pdo-pgsql").
397
            // Otherwise, let checkParams decide later if the driver exists.
398 484
            $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
399
400 484
            return $params;
401
        }
402
403
        // If a schemeless connection URL is given, we require a default driver or default custom driver
404
        // as connection parameter.
405 110
        if (! isset($params['driverClass']) && ! isset($params['driver'])) {
406 44
            throw DriverRequired::new($params['url']);
407
        }
408
409 66
        return $params;
410
    }
411
}
412