Completed
Push — develop ( 317415...dcb0ff )
by Sergei
23s queued 16s
created

DriverManager::getConnection()   B

Complexity

Conditions 8
Paths 48

Size

Total Lines 42
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 8

Importance

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