Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Illuminate\Database;
4
 
5
use Doctrine\DBAL\Types\Type;
6
use Illuminate\Database\Connectors\ConnectionFactory;
399 lars 7
use Illuminate\Database\Events\ConnectionEstablished;
148 lars 8
use Illuminate\Support\Arr;
9
use Illuminate\Support\ConfigurationUrlParser;
10
use Illuminate\Support\Str;
11
use Illuminate\Support\Traits\Macroable;
12
use InvalidArgumentException;
13
use PDO;
14
use RuntimeException;
15
 
16
/**
17
 * @mixin \Illuminate\Database\Connection
18
 */
19
class DatabaseManager implements ConnectionResolverInterface
20
{
21
    use Macroable {
22
        __call as macroCall;
23
    }
24
 
25
    /**
26
     * The application instance.
27
     *
28
     * @var \Illuminate\Contracts\Foundation\Application
29
     */
30
    protected $app;
31
 
32
    /**
33
     * The database connection factory instance.
34
     *
35
     * @var \Illuminate\Database\Connectors\ConnectionFactory
36
     */
37
    protected $factory;
38
 
39
    /**
40
     * The active connection instances.
41
     *
42
     * @var array<string, \Illuminate\Database\Connection>
43
     */
44
    protected $connections = [];
45
 
46
    /**
47
     * The custom connection resolvers.
48
     *
49
     * @var array<string, callable>
50
     */
51
    protected $extensions = [];
52
 
53
    /**
54
     * The callback to be executed to reconnect to a database.
55
     *
56
     * @var callable
57
     */
58
    protected $reconnector;
59
 
60
    /**
61
     * The custom Doctrine column types.
62
     *
63
     * @var array<string, array>
64
     */
65
    protected $doctrineTypes = [];
66
 
67
    /**
68
     * Create a new database manager instance.
69
     *
70
     * @param  \Illuminate\Contracts\Foundation\Application  $app
71
     * @param  \Illuminate\Database\Connectors\ConnectionFactory  $factory
72
     * @return void
73
     */
74
    public function __construct($app, ConnectionFactory $factory)
75
    {
76
        $this->app = $app;
77
        $this->factory = $factory;
78
 
79
        $this->reconnector = function ($connection) {
80
            $this->reconnect($connection->getNameWithReadWriteType());
81
        };
82
    }
83
 
84
    /**
85
     * Get a database connection instance.
86
     *
87
     * @param  string|null  $name
88
     * @return \Illuminate\Database\Connection
89
     */
90
    public function connection($name = null)
91
    {
92
        [$database, $type] = $this->parseConnectionName($name);
93
 
94
        $name = $name ?: $database;
95
 
96
        // If we haven't created this connection, we'll create it based on the config
97
        // provided in the application. Once we've created the connections we will
98
        // set the "fetch mode" for PDO which determines the query return types.
99
        if (! isset($this->connections[$name])) {
100
            $this->connections[$name] = $this->configure(
101
                $this->makeConnection($database), $type
102
            );
399 lars 103
 
104
            if ($this->app->bound('events')) {
105
                $this->app['events']->dispatch(
106
                    new ConnectionEstablished($this->connections[$name])
107
                );
108
            }
148 lars 109
        }
110
 
111
        return $this->connections[$name];
112
    }
113
 
114
    /**
115
     * Parse the connection into an array of the name and read / write type.
116
     *
117
     * @param  string  $name
118
     * @return array
119
     */
120
    protected function parseConnectionName($name)
121
    {
122
        $name = $name ?: $this->getDefaultConnection();
123
 
124
        return Str::endsWith($name, ['::read', '::write'])
125
                            ? explode('::', $name, 2) : [$name, null];
126
    }
127
 
128
    /**
129
     * Make the database connection instance.
130
     *
131
     * @param  string  $name
132
     * @return \Illuminate\Database\Connection
133
     */
134
    protected function makeConnection($name)
135
    {
136
        $config = $this->configuration($name);
137
 
138
        // First we will check by the connection name to see if an extension has been
139
        // registered specifically for that connection. If it has we will call the
140
        // Closure and pass it the config allowing it to resolve the connection.
141
        if (isset($this->extensions[$name])) {
142
            return call_user_func($this->extensions[$name], $config, $name);
143
        }
144
 
145
        // Next we will check to see if an extension has been registered for a driver
146
        // and will call the Closure if so, which allows us to have a more generic
147
        // resolver for the drivers themselves which applies to all connections.
148
        if (isset($this->extensions[$driver = $config['driver']])) {
149
            return call_user_func($this->extensions[$driver], $config, $name);
150
        }
151
 
152
        return $this->factory->make($config, $name);
153
    }
154
 
155
    /**
156
     * Get the configuration for a connection.
157
     *
158
     * @param  string  $name
159
     * @return array
160
     *
161
     * @throws \InvalidArgumentException
162
     */
163
    protected function configuration($name)
164
    {
165
        $name = $name ?: $this->getDefaultConnection();
166
 
167
        // To get the database connection configuration, we will just pull each of the
168
        // connection configurations and get the configurations for the given name.
169
        // If the configuration doesn't exist, we'll throw an exception and bail.
170
        $connections = $this->app['config']['database.connections'];
171
 
172
        if (is_null($config = Arr::get($connections, $name))) {
173
            throw new InvalidArgumentException("Database connection [{$name}] not configured.");
174
        }
175
 
176
        return (new ConfigurationUrlParser)
177
                    ->parseConfiguration($config);
178
    }
179
 
180
    /**
181
     * Prepare the database connection instance.
182
     *
183
     * @param  \Illuminate\Database\Connection  $connection
184
     * @param  string  $type
185
     * @return \Illuminate\Database\Connection
186
     */
187
    protected function configure(Connection $connection, $type)
188
    {
189
        $connection = $this->setPdoForType($connection, $type)->setReadWriteType($type);
190
 
191
        // First we'll set the fetch mode and a few other dependencies of the database
192
        // connection. This method basically just configures and prepares it to get
193
        // used by the application. Once we're finished we'll return it back out.
194
        if ($this->app->bound('events')) {
195
            $connection->setEventDispatcher($this->app['events']);
196
        }
197
 
198
        if ($this->app->bound('db.transactions')) {
199
            $connection->setTransactionManager($this->app['db.transactions']);
200
        }
201
 
202
        // Here we'll set a reconnector callback. This reconnector can be any callable
203
        // so we will set a Closure to reconnect from this manager with the name of
204
        // the connection, which will allow us to reconnect from the connections.
205
        $connection->setReconnector($this->reconnector);
206
 
207
        $this->registerConfiguredDoctrineTypes($connection);
208
 
209
        return $connection;
210
    }
211
 
212
    /**
213
     * Prepare the read / write mode for database connection instance.
214
     *
215
     * @param  \Illuminate\Database\Connection  $connection
216
     * @param  string|null  $type
217
     * @return \Illuminate\Database\Connection
218
     */
219
    protected function setPdoForType(Connection $connection, $type = null)
220
    {
221
        if ($type === 'read') {
222
            $connection->setPdo($connection->getReadPdo());
223
        } elseif ($type === 'write') {
224
            $connection->setReadPdo($connection->getPdo());
225
        }
226
 
227
        return $connection;
228
    }
229
 
230
    /**
231
     * Register custom Doctrine types with the connection.
232
     *
233
     * @param  \Illuminate\Database\Connection  $connection
234
     * @return void
235
     */
236
    protected function registerConfiguredDoctrineTypes(Connection $connection): void
237
    {
238
        foreach ($this->app['config']->get('database.dbal.types', []) as $name => $class) {
239
            $this->registerDoctrineType($class, $name, $name);
240
        }
241
 
242
        foreach ($this->doctrineTypes as $name => [$type, $class]) {
243
            $connection->registerDoctrineType($class, $name, $type);
244
        }
245
    }
246
 
247
    /**
248
     * Register a custom Doctrine type.
249
     *
250
     * @param  string  $class
251
     * @param  string  $name
252
     * @param  string  $type
253
     * @return void
254
     *
255
     * @throws \Doctrine\DBAL\DBALException
256
     * @throws \RuntimeException
257
     */
258
    public function registerDoctrineType(string $class, string $name, string $type): void
259
    {
260
        if (! class_exists('Doctrine\DBAL\Connection')) {
261
            throw new RuntimeException(
262
                'Registering a custom Doctrine type requires Doctrine DBAL (doctrine/dbal).'
263
            );
264
        }
265
 
266
        if (! Type::hasType($name)) {
267
            Type::addType($name, $class);
268
        }
269
 
270
        $this->doctrineTypes[$name] = [$type, $class];
271
    }
272
 
273
    /**
274
     * Disconnect from the given database and remove from local cache.
275
     *
276
     * @param  string|null  $name
277
     * @return void
278
     */
279
    public function purge($name = null)
280
    {
281
        $name = $name ?: $this->getDefaultConnection();
282
 
283
        $this->disconnect($name);
284
 
285
        unset($this->connections[$name]);
286
    }
287
 
288
    /**
289
     * Disconnect from the given database.
290
     *
291
     * @param  string|null  $name
292
     * @return void
293
     */
294
    public function disconnect($name = null)
295
    {
296
        if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) {
297
            $this->connections[$name]->disconnect();
298
        }
299
    }
300
 
301
    /**
302
     * Reconnect to the given database.
303
     *
304
     * @param  string|null  $name
305
     * @return \Illuminate\Database\Connection
306
     */
307
    public function reconnect($name = null)
308
    {
309
        $this->disconnect($name = $name ?: $this->getDefaultConnection());
310
 
311
        if (! isset($this->connections[$name])) {
312
            return $this->connection($name);
313
        }
314
 
315
        return $this->refreshPdoConnections($name);
316
    }
317
 
318
    /**
319
     * Set the default database connection for the callback execution.
320
     *
321
     * @param  string  $name
322
     * @param  callable  $callback
323
     * @return mixed
324
     */
325
    public function usingConnection($name, callable $callback)
326
    {
327
        $previousName = $this->getDefaultConnection();
328
 
329
        $this->setDefaultConnection($name);
330
 
331
        return tap($callback(), function () use ($previousName) {
332
            $this->setDefaultConnection($previousName);
333
        });
334
    }
335
 
336
    /**
337
     * Refresh the PDO connections on a given connection.
338
     *
339
     * @param  string  $name
340
     * @return \Illuminate\Database\Connection
341
     */
342
    protected function refreshPdoConnections($name)
343
    {
344
        [$database, $type] = $this->parseConnectionName($name);
345
 
346
        $fresh = $this->configure(
347
            $this->makeConnection($database), $type
348
        );
349
 
350
        return $this->connections[$name]
351
                    ->setPdo($fresh->getRawPdo())
352
                    ->setReadPdo($fresh->getRawReadPdo());
353
    }
354
 
355
    /**
356
     * Get the default connection name.
357
     *
358
     * @return string
359
     */
360
    public function getDefaultConnection()
361
    {
362
        return $this->app['config']['database.default'];
363
    }
364
 
365
    /**
366
     * Set the default connection name.
367
     *
368
     * @param  string  $name
369
     * @return void
370
     */
371
    public function setDefaultConnection($name)
372
    {
373
        $this->app['config']['database.default'] = $name;
374
    }
375
 
376
    /**
377
     * Get all of the support drivers.
378
     *
379
     * @return string[]
380
     */
381
    public function supportedDrivers()
382
    {
383
        return ['mysql', 'pgsql', 'sqlite', 'sqlsrv'];
384
    }
385
 
386
    /**
387
     * Get all of the drivers that are actually available.
388
     *
389
     * @return string[]
390
     */
391
    public function availableDrivers()
392
    {
393
        return array_intersect(
394
            $this->supportedDrivers(),
395
            str_replace('dblib', 'sqlsrv', PDO::getAvailableDrivers())
396
        );
397
    }
398
 
399
    /**
400
     * Register an extension connection resolver.
401
     *
402
     * @param  string  $name
403
     * @param  callable  $resolver
404
     * @return void
405
     */
406
    public function extend($name, callable $resolver)
407
    {
408
        $this->extensions[$name] = $resolver;
409
    }
410
 
411
    /**
412
     * Remove an extension connection resolver.
413
     *
414
     * @param  string  $name
415
     * @return void
416
     */
417
    public function forgetExtension($name)
418
    {
419
        unset($this->extensions[$name]);
420
    }
421
 
422
    /**
423
     * Return all of the created connections.
424
     *
425
     * @return array<string, \Illuminate\Database\Connection>
426
     */
427
    public function getConnections()
428
    {
429
        return $this->connections;
430
    }
431
 
432
    /**
433
     * Set the database reconnector callback.
434
     *
435
     * @param  callable  $reconnector
436
     * @return void
437
     */
438
    public function setReconnector(callable $reconnector)
439
    {
440
        $this->reconnector = $reconnector;
441
    }
442
 
443
    /**
444
     * Set the application instance used by the manager.
445
     *
446
     * @param  \Illuminate\Contracts\Foundation\Application  $app
447
     * @return $this
448
     */
449
    public function setApplication($app)
450
    {
451
        $this->app = $app;
452
 
453
        return $this;
454
    }
455
 
456
    /**
457
     * Dynamically pass methods to the default connection.
458
     *
459
     * @param  string  $method
460
     * @param  array  $parameters
461
     * @return mixed
462
     */
463
    public function __call($method, $parameters)
464
    {
465
        if (static::hasMacro($method)) {
466
            return $this->macroCall($method, $parameters);
467
        }
468
 
469
        return $this->connection()->$method(...$parameters);
470
    }
471
}