Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 621 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

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