Passed
Pull Request — master (#3070)
by Sergei
07:45
created

DriverManager::parseDatabaseUrl()   B

Complexity

Conditions 7
Paths 18

Size

Total Lines 40
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 7.0052

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 40
ccs 20
cts 21
cp 0.9524
rs 8.6666
c 0
b 0
f 0
cc 7
nc 18
nop 1
crap 7.0052
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 2984
    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 2984
        if (! $config) {
146 2781
            $config = new Configuration();
147
        }
148
149 2984
        if (! $eventManager) {
150 2781
            $eventManager = new EventManager();
151
        }
152
153 2984
        $params = self::parseDatabaseUrl($params);
154
155
        // URL support for MasterSlaveConnection
156 2930
        if (isset($params['master'])) {
157 153
            $params['master'] = self::parseDatabaseUrl($params['master']);
158
        }
159
160 2930
        if (isset($params['slaves'])) {
161 153
            foreach ($params['slaves'] as $key => $slaveParams) {
162 153
                $params['slaves'][$key] = self::parseDatabaseUrl($slaveParams);
163
            }
164
        }
165
166 2930
        self::_checkParams($params);
167
168 2849
        $className = $params['driverClass'] ?? self::$_driverMap[$params['driver']];
169
170 2849
        $driver = new $className();
171
172 2849
        $wrapperClass = Connection::class;
173 2849
        if (isset($params['wrapperClass'])) {
174 342
            if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
175 27
                throw InvalidWrapperClass::new($params['wrapperClass']);
176
            }
177
178 315
            $wrapperClass = $params['wrapperClass'];
179
        }
180
181 2822
        return new $wrapperClass($params, $driver, $config, $eventManager);
182
    }
183
184
    /**
185
     * Returns the list of supported drivers.
186
     *
187
     * @return string[]
188
     */
189
    public static function getAvailableDrivers() : array
190
    {
191
        return array_keys(self::$_driverMap);
192
    }
193
194
    /**
195
     * Checks the list of parameters.
196
     *
197
     * @param mixed[] $params The list of parameters.
198
     *
199
     * @throws DBALException
200
     */
201 2930
    private static function _checkParams(array $params) : void
202
    {
203
        // check existence of mandatory parameters
204
205
        // driver
206 2930
        if (! isset($params['driver']) && ! isset($params['driverClass'])) {
207 27
            throw DriverRequired::new();
208
        }
209
210
        // check validity of parameters
211
212
        // driver
213 2903
        if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
214 27
            throw UnknownDriver::new($params['driver'], array_keys(self::$_driverMap));
215
        }
216
217 2876
        if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) {
218 27
            throw InvalidDriverClass::new($params['driverClass']);
219
        }
220 2849
    }
221
222
    /**
223
     * Normalizes the given connection URL path.
224
     *
225
     * @return string The normalized connection URL path
226
     */
227 675
    private static function normalizeDatabaseUrlPath(string $urlPath) : string
228
    {
229
        // Trim leading slash from URL path.
230 675
        return substr($urlPath, 1);
231
    }
232
233
    /**
234
     * Extracts parts from a database URL, if present, and returns an
235
     * updated list of parameters.
236
     *
237
     * @param mixed[] $params The list of parameters.
238
     *
239
     * @return mixed[] A modified list of parameters with info from a database
240
     *                 URL extracted into indidivual parameter parts.
241
     *
242
     * @throws DBALException
243
     */
244 2984
    private static function parseDatabaseUrl(array $params) : array
245
    {
246 2984
        if (! isset($params['url'])) {
247 2282
            return $params;
248
        }
249
250
        // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
251 729
        $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
252 729
        assert(is_string($url));
253
254 729
        $url = parse_url($url);
255
256 729
        if ($url === false) {
257
            throw new DBALException('Malformed parameter "url".');
258
        }
259
260 729
        $url = array_map('rawurldecode', $url);
261
262 729
        $params = self::parseDatabaseUrlScheme($url, $params);
263
264 675
        if (isset($url['host'])) {
265 594
            $params['host'] = $url['host'];
266
        }
267
268 675
        if (isset($url['port'])) {
269 54
            $params['port'] = $url['port'];
270
        }
271
272 675
        if (isset($url['user'])) {
273 432
            $params['user'] = $url['user'];
274
        }
275
276 675
        if (isset($url['pass'])) {
277 432
            $params['password'] = $url['pass'];
278
        }
279
280 675
        $params = self::parseDatabaseUrlPath($url, $params);
281 675
        $params = self::parseDatabaseUrlQuery($url, $params);
282
283 675
        return $params;
284
    }
285
286
    /**
287
     * Parses the given connection URL and resolves the given connection parameters.
288
     *
289
     * Assumes that the connection URL scheme is already parsed and resolved into the given connection parameters
290
     * via {@link parseDatabaseUrlScheme}.
291
     *
292
     * @see parseDatabaseUrlScheme
293
     *
294
     * @param mixed[] $url    The URL parts to evaluate.
295
     * @param mixed[] $params The connection parameters to resolve.
296
     *
297
     * @return mixed[] The resolved connection parameters.
298
     */
299 675
    private static function parseDatabaseUrlPath(array $url, array $params) : array
300
    {
301 675
        if (! isset($url['path'])) {
302
            return $params;
303
        }
304
305 675
        $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
306
307
        // If we do not have a known DBAL driver, we do not know any connection URL path semantics to evaluate
308
        // and therefore treat the path as regular DBAL connection URL path.
309 675
        if (! isset($params['driver'])) {
310 27
            return self::parseRegularDatabaseUrlPath($url, $params);
311
        }
312
313 648
        if (strpos($params['driver'], 'sqlite') !== false) {
314 243
            return self::parseSqliteDatabaseUrlPath($url, $params);
315
        }
316
317 405
        return self::parseRegularDatabaseUrlPath($url, $params);
318
    }
319
320
    /**
321
     * Parses the query part of the given connection URL and resolves the given connection parameters.
322
     *
323
     * @param mixed[] $url    The connection URL parts to evaluate.
324
     * @param mixed[] $params The connection parameters to resolve.
325
     *
326
     * @return mixed[] The resolved connection parameters.
327
     */
328 675
    private static function parseDatabaseUrlQuery(array $url, array $params) : array
329
    {
330 675
        if (! isset($url['query'])) {
331 648
            return $params;
332
        }
333
334 27
        $query = [];
335
336 27
        parse_str($url['query'], $query); // simply ingest query as extra params, e.g. charset or sslmode
337
338 27
        return array_merge($params, $query); // parse_str wipes existing array elements
339
    }
340
341
    /**
342
     * Parses the given regular connection URL and resolves the given connection parameters.
343
     *
344
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
345
     *
346
     * @see normalizeDatabaseUrlPath
347
     *
348
     * @param mixed[] $url    The regular connection URL parts to evaluate.
349
     * @param mixed[] $params The connection parameters to resolve.
350
     *
351
     * @return mixed[] The resolved connection parameters.
352
     */
353 432
    private static function parseRegularDatabaseUrlPath(array $url, array $params) : array
354
    {
355 432
        $params['dbname'] = $url['path'];
356
357 432
        return $params;
358
    }
359
360
    /**
361
     * Parses the given SQLite connection URL and resolves the given connection parameters.
362
     *
363
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
364
     *
365
     * @see normalizeDatabaseUrlPath
366
     *
367
     * @param mixed[] $url    The SQLite connection URL parts to evaluate.
368
     * @param mixed[] $params The connection parameters to resolve.
369
     *
370
     * @return mixed[] The resolved connection parameters.
371
     */
372 243
    private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array
373
    {
374 243
        if ($url['path'] === ':memory:') {
375 54
            $params['memory'] = true;
376
377 54
            return $params;
378
        }
379
380 189
        $params['path'] = $url['path']; // pdo_sqlite driver uses 'path' instead of 'dbname' key
381
382 189
        return $params;
383
    }
384
385
    /**
386
     * Parses the scheme part from given connection URL and resolves the given connection parameters.
387
     *
388
     * @param mixed[] $url    The connection URL parts to evaluate.
389
     * @param mixed[] $params The connection parameters to resolve.
390
     *
391
     * @return mixed[] The resolved connection parameters.
392
     *
393
     * @throws DBALException If parsing failed or resolution is not possible.
394
     */
395 729
    private static function parseDatabaseUrlScheme(array $url, array $params) : array
396
    {
397 729
        if (isset($url['scheme'])) {
398
            // The requested driver from the URL scheme takes precedence
399
            // over the default custom driver from the connection parameters (if any).
400 594
            unset($params['driverClass']);
401
402
            // URL schemes must not contain underscores, but dashes are ok
403 594
            $driver = str_replace('-', '_', $url['scheme']);
404 594
            assert(is_string($driver));
405
406
            // The requested driver from the URL scheme takes precedence over the
407
            // default driver from the connection parameters. If the driver is
408
            // an alias (e.g. "postgres"), map it to the actual name ("pdo-pgsql").
409
            // Otherwise, let checkParams decide later if the driver exists.
410 594
            $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
411
412 594
            return $params;
413
        }
414
415
        // If a schemeless connection URL is given, we require a default driver or default custom driver
416
        // as connection parameter.
417 135
        if (! isset($params['driverClass']) && ! isset($params['driver'])) {
418 54
            throw DriverRequired::new($params['url']);
419
        }
420
421 81
        return $params;
422
    }
423
}
424