forked from doctrine/DoctrineBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionFactory.php
285 lines (241 loc) · 10.4 KB
/
ConnectionFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
namespace Doctrine\Bundle\DoctrineBundle;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Connection\StaticServerVersionProvider;
use Doctrine\DBAL\ConnectionException;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Exception as DBALException;
use Doctrine\DBAL\Exception\DriverException;
use Doctrine\DBAL\Exception\DriverRequired;
use Doctrine\DBAL\Exception\InvalidWrapperClass;
use Doctrine\DBAL\Exception\MalformedDsnException;
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Tools\DsnParser;
use Doctrine\DBAL\Types\Type;
use Doctrine\Deprecations\Deprecation;
use InvalidArgumentException;
use function array_merge;
use function class_exists;
use function is_subclass_of;
use function method_exists;
use function trigger_deprecation;
use const PHP_EOL;
/** @psalm-import-type Params from DriverManager */
class ConnectionFactory
{
/** @internal */
public const DEFAULT_SCHEME_MAP = [
'db2' => 'ibm_db2',
'mssql' => 'pdo_sqlsrv',
'mysql' => 'pdo_mysql',
'mysql2' => 'pdo_mysql', // Amazon RDS, for some weird reason
'postgres' => 'pdo_pgsql',
'postgresql' => 'pdo_pgsql',
'pgsql' => 'pdo_pgsql',
'sqlite' => 'pdo_sqlite',
'sqlite3' => 'pdo_sqlite',
];
/** @var mixed[][] */
private array $typesConfig = [];
private DsnParser $dsnParser;
private bool $initialized = false;
/** @param mixed[][] $typesConfig */
public function __construct(array $typesConfig, ?DsnParser $dsnParser = null)
{
$this->typesConfig = $typesConfig;
$this->dsnParser = $dsnParser ?? new DsnParser(self::DEFAULT_SCHEME_MAP);
}
/**
* Create a connection by name.
*
* @param mixed[] $params
* @param array<string, string> $mappingTypes
* @psalm-param Params $params
*
* @return Connection
*/
public function createConnection(array $params, ?Configuration $config = null, ?EventManager $eventManager = null, array $mappingTypes = [])
{
if (! method_exists(Connection::class, 'getEventManager') && $eventManager !== null) {
throw new InvalidArgumentException('Passing an EventManager instance is not supported with DBAL > 3');
}
if (! $this->initialized) {
$this->initializeTypes();
}
$overriddenOptions = [];
/** @psalm-suppress InvalidArrayOffset We should adjust when https://github.com/vimeo/psalm/issues/8984 is fixed */
if (isset($params['connection_override_options'])) {
trigger_deprecation('doctrine/doctrine-bundle', '2.4', 'The "connection_override_options" connection parameter is deprecated');
$overriddenOptions = $params['connection_override_options'];
unset($params['connection_override_options']);
}
$params = $this->parseDatabaseUrl($params);
// URL support for PrimaryReplicaConnection
if (isset($params['primary'])) {
$params['primary'] = $this->parseDatabaseUrl($params['primary']);
}
if (isset($params['replica'])) {
foreach ($params['replica'] as $key => $replicaParams) {
$params['replica'][$key] = $this->parseDatabaseUrl($replicaParams);
}
}
/** @psalm-suppress InvalidArrayOffset We should adjust when https://github.com/vimeo/psalm/issues/8984 is fixed */
if (! isset($params['pdo']) && (! isset($params['charset']) || $overriddenOptions || isset($params['dbname_suffix']))) {
$wrapperClass = null;
if (isset($params['wrapperClass'])) {
if (! is_subclass_of($params['wrapperClass'], Connection::class)) {
if (class_exists(InvalidWrapperClass::class)) {
throw InvalidWrapperClass::new($params['wrapperClass']);
}
throw DBALException::invalidWrapperClass($params['wrapperClass']);
}
$wrapperClass = $params['wrapperClass'];
$params['wrapperClass'] = null;
}
$connection = DriverManager::getConnection(...array_merge([$params, $config], $eventManager ? [$eventManager] : []));
$params = $this->addDatabaseSuffix(array_merge($connection->getParams(), $overriddenOptions));
$driver = $connection->getDriver();
$platform = $driver->getDatabasePlatform(
...(class_exists(StaticServerVersionProvider::class) ? [new StaticServerVersionProvider($params['serverVersion'] ?? '')] : []),
);
if (! isset($params['charset'])) {
if ($platform instanceof AbstractMySQLPlatform) {
$params['charset'] = 'utf8mb4';
if (isset($params['defaultTableOptions']['collate'])) {
Deprecation::trigger(
'doctrine/doctrine-bundle',
'https://github.com/doctrine/dbal/issues/5214',
'The "collate" default table option is deprecated in favor of "collation" and will be removed in doctrine/doctrine-bundle 3.0. ',
);
$params['defaultTableOptions']['collation'] = $params['defaultTableOptions']['collate'];
unset($params['defaultTableOptions']['collate']);
}
if (! isset($params['defaultTableOptions']['collation'])) {
$params['defaultTableOptions']['collation'] = 'utf8mb4_unicode_ci';
}
} else {
$params['charset'] = 'utf8';
}
}
if ($wrapperClass !== null) {
$params['wrapperClass'] = $wrapperClass;
} else {
$wrapperClass = Connection::class;
}
$connection = new $wrapperClass($params, $driver, $config, $eventManager);
} else {
$connection = DriverManager::getConnection(...array_merge([$params, $config], $eventManager ? [$eventManager] : []));
}
if (! empty($mappingTypes)) {
$platform = $this->getDatabasePlatform($connection);
foreach ($mappingTypes as $dbType => $doctrineType) {
$platform->registerDoctrineTypeMapping($dbType, $doctrineType);
}
}
return $connection;
}
/**
* Try to get the database platform.
*
* This could fail if types should be registered to an predefined/unused connection
* and the platform version is unknown.
*
* @link https://github.com/doctrine/DoctrineBundle/issues/673
*
* @throws DBALException
*/
private function getDatabasePlatform(Connection $connection): AbstractPlatform
{
try {
return $connection->getDatabasePlatform();
} catch (DriverException $driverException) {
$class = class_exists(DBALException::class) ? DBALException::class : ConnectionException::class;
throw new $class(
'An exception occurred while establishing a connection to figure out your platform version.' . PHP_EOL .
"You can circumvent this by setting a 'server_version' configuration value" . PHP_EOL . PHP_EOL .
'For further information have a look at:' . PHP_EOL .
'https://github.com/doctrine/DoctrineBundle/issues/673',
0,
$driverException,
);
}
}
/**
* initialize the types
*/
private function initializeTypes(): void
{
foreach ($this->typesConfig as $typeName => $typeConfig) {
if (Type::hasType($typeName)) {
Type::overrideType($typeName, $typeConfig['class']);
} else {
Type::addType($typeName, $typeConfig['class']);
}
}
$this->initialized = true;
}
/**
* @param array<string, mixed> $params
*
* @return array<string, mixed>
*/
private function addDatabaseSuffix(array $params): array
{
if (isset($params['dbname']) && isset($params['dbname_suffix'])) {
$params['dbname'] .= $params['dbname_suffix'];
}
foreach ($params['replica'] ?? [] as $key => $replicaParams) {
if (! isset($replicaParams['dbname'], $replicaParams['dbname_suffix'])) {
continue;
}
$params['replica'][$key]['dbname'] .= $replicaParams['dbname_suffix'];
}
if (isset($params['primary']['dbname'], $params['primary']['dbname_suffix'])) {
$params['primary']['dbname'] .= $params['primary']['dbname_suffix'];
}
return $params;
}
/**
* Extracts parts from a database URL, if present, and returns an
* updated list of parameters.
*
* @param mixed[] $params The list of parameters.
* @psalm-param Params $params
*
* @return mixed[] A modified list of parameters with info from a database
* URL extracted into individual parameter parts.
* @psalm-return Params
*
* @throws DBALException
*/
private function parseDatabaseUrl(array $params): array
{
if (! isset($params['url'])) {
return $params;
}
try {
$parsedParams = $this->dsnParser->parse($params['url']);
} catch (MalformedDsnException $e) {
throw new MalformedDsnException('Malformed parameter "url".', 0, $e);
}
if (isset($parsedParams['driver'])) {
// The requested driver from the URL scheme takes precedence
// over the default custom driver from the connection parameters (if any).
unset($params['driverClass']);
}
$params = array_merge($params, $parsedParams);
// If a schemeless connection URL is given, we require a default driver or default custom driver
// as connection parameter.
if (! isset($params['driverClass']) && ! isset($params['driver'])) {
if (class_exists(DriverRequired::class)) {
throw DriverRequired::new($params['url']);
}
throw DBALException::driverRequired($params['url']);
}
unset($params['url']);
return $params;
}
}