Completed
Push — master ( 7f79d0...1c7523 )
by Sergei
25:19 queued 22:43
created

DriverManager   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 403
Duplicated Lines 0 %

Test Coverage

Coverage 94%

Importance

Changes 0
Metric Value
wmc 44
eloc 110
dl 0
loc 403
ccs 94
cts 100
cp 0.94
rs 8.8798
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
B _checkParams() 0 18 7
A parseSqliteDatabaseUrlPath() 0 11 2
A getAvailableDrivers() 0 3 1
B parseDatabaseUrl() 0 41 7
A parseDatabaseUrlQuery() 0 11 2
A parseDatabaseUrlPath() 0 19 4
A normalizeDatabaseUrlPath() 0 4 1
A parseDatabaseUrlScheme() 0 27 4
F getConnection() 0 61 14
A parseRegularDatabaseUrlPath() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like DriverManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DriverManager, and based on these observations, apply Extract Interface, too.

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