Completed
Push — 2.11.x ( 0a2e2f...a8544c )
by Grégoire
23s queued 16s
created

DriverManager   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 396
Duplicated Lines 0 %

Test Coverage

Coverage 94%

Importance

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

11 Methods

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

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 array keys of {@link $_driverMap},
92
     * OR 'driverClass' that contains the full class name (with namespace) of the
93
     * driver class to instantiate.
94
     *
95
     * Other (optional) parameters:
96
     *
97
     * <b>user (string)</b>:
98
     * The username to use when connecting.
99
     *
100
     * <b>password (string)</b>:
101
     * The password to use when connecting.
102
     *
103
     * <b>driverOptions (array)</b>:
104
     * Any additional driver-specific options for the driver. These are just passed
105
     * through to the driver.
106
     *
107
     * <b>pdo</b>:
108
     * You can pass an existing PDO instance through this parameter. The PDO
109
     * instance will be wrapped in a Doctrine\DBAL\Connection.
110
     *
111
     * <b>wrapperClass</b>:
112
     * You may specify a custom wrapper class through the 'wrapperClass'
113
     * parameter but this class MUST inherit from Doctrine\DBAL\Connection.
114
     *
115
     * <b>driverClass</b>:
116
     * The driver class to use.
117
     *
118
     * @param mixed[]            $params       The parameters.
119
     * @param Configuration|null $config       The configuration to use.
120
     * @param EventManager|null  $eventManager The event manager to use.
121
     *
122
     * @throws DBALException
123
     */
124 2965
    public static function getConnection(
125
        array $params,
126
        ?Configuration $config = null,
127
        ?EventManager $eventManager = null
128
    ) : Connection {
129
        // create default config and event manager, if not set
130 2965
        if (! $config) {
131 2958
            $config = new Configuration();
132
        }
133
134 2965
        if (! $eventManager) {
135 2958
            $eventManager = new EventManager();
136
        }
137
138 2965
        $params = self::parseDatabaseUrl($params);
139
140
        // URL support for MasterSlaveConnection
141 2962
        if (isset($params['master'])) {
142 1616
            $params['master'] = self::parseDatabaseUrl($params['master']);
143
        }
144
145 2962
        if (isset($params['slaves'])) {
146 1616
            foreach ($params['slaves'] as $key => $slaveParams) {
147 1616
                $params['slaves'][$key] = self::parseDatabaseUrl($slaveParams);
148
            }
149
        }
150
151
        // URL support for PoolingShardConnection
152 2962
        if (isset($params['global'])) {
153 1607
            $params['global'] = self::parseDatabaseUrl($params['global']);
154
        }
155
156 2962
        if (isset($params['shards'])) {
157 1607
            foreach ($params['shards'] as $key => $shardParams) {
158 1607
                $params['shards'][$key] = self::parseDatabaseUrl($shardParams);
159
            }
160
        }
161
162
        // check for existing pdo object
163 2962
        if (isset($params['pdo']) && ! $params['pdo'] instanceof PDO) {
164 1846
            throw DBALException::invalidPdoInstance();
165
        }
166
167 2961
        if (isset($params['pdo'])) {
168 1828
            $params['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
169 1828
            $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(PDO::ATTR_DRIVER_NAME);
170
        } else {
171 2956
            self::_checkParams($params);
172
        }
173
174 2958
        $className = $params['driverClass'] ?? self::$_driverMap[$params['driver']];
175
176 2958
        $driver = new $className();
177
178 2958
        $wrapperClass = Connection::class;
179 2958
        if (isset($params['wrapperClass'])) {
180 1731
            if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
181 1685
                throw DBALException::invalidWrapperClass($params['wrapperClass']);
182
            }
183
184 1730
            $wrapperClass = $params['wrapperClass'];
185
        }
186
187 2957
        return new $wrapperClass($params, $driver, $config, $eventManager);
188
    }
189
190
    /**
191
     * Returns the list of supported drivers.
192
     *
193
     * @return string[]
194
     */
195
    public static function getAvailableDrivers() : array
196
    {
197
        return array_keys(self::$_driverMap);
198
    }
199
200
    /**
201
     * Checks the list of parameters.
202
     *
203
     * @param mixed[] $params The list of parameters.
204
     *
205
     * @throws DBALException
206
     */
207 2956
    private static function _checkParams(array $params) : void
208
    {
209
        // check existence of mandatory parameters
210
211
        // driver
212 2956
        if (! isset($params['driver']) && ! isset($params['driverClass'])) {
213 1777
            throw DBALException::driverRequired();
214
        }
215
216
        // check validity of parameters
217
218
        // driver
219 2955
        if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
220 1754
            throw DBALException::unknownDriver($params['driver'], array_keys(self::$_driverMap));
221
        }
222
223 2954
        if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) {
224 1662
            throw DBALException::invalidDriverClass($params['driverClass']);
225
        }
226 2953
    }
227
228
    /**
229
     * Normalizes the given connection URL path.
230
     *
231
     * @return string The normalized connection URL path
232
     */
233 1642
    private static function normalizeDatabaseUrlPath(string $urlPath) : string
234
    {
235
        // Trim leading slash from URL path.
236 1642
        return substr($urlPath, 1);
237
    }
238
239
    /**
240
     * Extracts parts from a database URL, if present, and returns an
241
     * updated list of parameters.
242
     *
243
     * @param mixed[] $params The list of parameters.
244
     *
245
     * @return mixed[] A modified list of parameters with info from a database
246
     *                 URL extracted into indidivual parameter parts.
247
     *
248
     * @throws DBALException
249
     */
250 2965
    private static function parseDatabaseUrl(array $params) : array
251
    {
252 2965
        if (! isset($params['url'])) {
253 2937
            return $params;
254
        }
255
256
        // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
257 1645
        $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
258 1645
        assert(is_string($url));
259
260 1645
        $url = parse_url($url);
261
262 1645
        if ($url === false) {
263
            throw new DBALException('Malformed parameter "url".');
264
        }
265
266 1645
        $url = array_map('rawurldecode', $url);
267
268
        // If we have a connection URL, we have to unset the default PDO instance connection parameter (if any)
269
        // as we cannot merge connection details from the URL into the PDO instance (URL takes precedence).
270 1645
        unset($params['pdo']);
271
272 1645
        $params = self::parseDatabaseUrlScheme($url, $params);
273
274 1642
        if (isset($url['host'])) {
275 1642
            $params['host'] = $url['host'];
276
        }
277
278 1642
        if (isset($url['port'])) {
279 1618
            $params['port'] = $url['port'];
280
        }
281
282 1642
        if (isset($url['user'])) {
283 1636
            $params['user'] = $url['user'];
284
        }
285
286 1642
        if (isset($url['pass'])) {
287 1636
            $params['password'] = $url['pass'];
288
        }
289
290 1642
        $params = self::parseDatabaseUrlPath($url, $params);
291 1642
        $params = self::parseDatabaseUrlQuery($url, $params);
292
293 1642
        return $params;
294
    }
295
296
    /**
297
     * Parses the given connection URL and resolves the given connection parameters.
298
     *
299
     * Assumes that the connection URL scheme is already parsed and resolved into the given connection parameters
300
     * via {@link parseDatabaseUrlScheme}.
301
     *
302
     * @see parseDatabaseUrlScheme
303
     *
304
     * @param mixed[] $url    The URL parts to evaluate.
305
     * @param mixed[] $params The connection parameters to resolve.
306
     *
307
     * @return mixed[] The resolved connection parameters.
308
     */
309 1642
    private static function parseDatabaseUrlPath(array $url, array $params) : array
310
    {
311 1642
        if (! isset($url['path'])) {
312
            return $params;
313
        }
314
315 1642
        $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
316
317
        // If we do not have a known DBAL driver, we do not know any connection URL path semantics to evaluate
318
        // and therefore treat the path as regular DBAL connection URL path.
319 1642
        if (! isset($params['driver'])) {
320 1294
            return self::parseRegularDatabaseUrlPath($url, $params);
321
        }
322
323 1641
        if (strpos($params['driver'], 'sqlite') !== false) {
324 1529
            return self::parseSqliteDatabaseUrlPath($url, $params);
325
        }
326
327 1635
        return self::parseRegularDatabaseUrlPath($url, $params);
328
    }
329
330
    /**
331
     * Parses the query part of the given connection URL and resolves the given connection parameters.
332
     *
333
     * @param mixed[] $url    The connection URL parts to evaluate.
334
     * @param mixed[] $params The connection parameters to resolve.
335
     *
336
     * @return mixed[] The resolved connection parameters.
337
     */
338 1642
    private static function parseDatabaseUrlQuery(array $url, array $params) : array
339
    {
340 1642
        if (! isset($url['query'])) {
341 1641
            return $params;
342
        }
343
344 1455
        $query = [];
345
346 1455
        parse_str($url['query'], $query); // simply ingest query as extra params, e.g. charset or sslmode
347
348 1455
        return array_merge($params, $query); // parse_str wipes existing array elements
349
    }
350
351
    /**
352
     * Parses the given regular connection URL and resolves the given connection parameters.
353
     *
354
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
355
     *
356
     * @see normalizeDatabaseUrlPath
357
     *
358
     * @param mixed[] $url    The regular connection URL parts to evaluate.
359
     * @param mixed[] $params The connection parameters to resolve.
360
     *
361
     * @return mixed[] The resolved connection parameters.
362
     */
363 1636
    private static function parseRegularDatabaseUrlPath(array $url, array $params) : array
364
    {
365 1636
        $params['dbname'] = $url['path'];
366
367 1636
        return $params;
368
    }
369
370
    /**
371
     * Parses the given SQLite connection URL and resolves the given connection parameters.
372
     *
373
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
374
     *
375
     * @see normalizeDatabaseUrlPath
376
     *
377
     * @param mixed[] $url    The SQLite connection URL parts to evaluate.
378
     * @param mixed[] $params The connection parameters to resolve.
379
     *
380
     * @return mixed[] The resolved connection parameters.
381
     */
382 1529
    private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array
383
    {
384 1529
        if ($url['path'] === ':memory:') {
385 1502
            $params['memory'] = true;
386
387 1502
            return $params;
388
        }
389
390 1527
        $params['path'] = $url['path']; // pdo_sqlite driver uses 'path' instead of 'dbname' key
391
392 1527
        return $params;
393
    }
394
395
    /**
396
     * Parses the scheme part from given connection URL and resolves the given connection parameters.
397
     *
398
     * @param mixed[] $url    The connection URL parts to evaluate.
399
     * @param mixed[] $params The connection parameters to resolve.
400
     *
401
     * @return mixed[] The resolved connection parameters.
402
     *
403
     * @throws DBALException If parsing failed or resolution is not possible.
404
     */
405 1645
    private static function parseDatabaseUrlScheme(array $url, array $params) : array
406
    {
407 1645
        if (isset($url['scheme'])) {
408
            // The requested driver from the URL scheme takes precedence
409
            // over the default custom driver from the connection parameters (if any).
410 1638
            unset($params['driverClass']);
411
412
            // URL schemes must not contain underscores, but dashes are ok
413 1638
            $driver = str_replace('-', '_', $url['scheme']);
414 1638
            assert(is_string($driver));
415
416
            // The requested driver from the URL scheme takes precedence over the
417
            // default driver from the connection parameters. If the driver is
418
            // an alias (e.g. "postgres"), map it to the actual name ("pdo-pgsql").
419
            // Otherwise, let checkParams decide later if the driver exists.
420 1638
            $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
421
422 1638
            return $params;
423
        }
424
425
        // If a schemeless connection URL is given, we require a default driver or default custom driver
426
        // as connection parameter.
427 1415
        if (! isset($params['driverClass']) && ! isset($params['driver'])) {
428 1411
            throw DBALException::driverRequired($params['url']);
429
        }
430
431 1320
        return $params;
432
    }
433
}
434