forked from php-enqueue/enqueue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectionFactoryFactory.php
77 lines (61 loc) · 2.43 KB
/
ConnectionFactoryFactory.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
<?php
namespace Enqueue;
use Enqueue\Dsn\Dsn;
use Interop\Queue\ConnectionFactory;
final class ConnectionFactoryFactory implements ConnectionFactoryFactoryInterface
{
public function create($config): ConnectionFactory
{
if (is_string($config)) {
$config = ['dsn' => $config];
}
if (false == is_array($config)) {
throw new \InvalidArgumentException('The config must be either array or DSN string.');
}
if (false == array_key_exists('dsn', $config)) {
throw new \InvalidArgumentException('The config must have dsn key set.');
}
$dsn = Dsn::parseFirst($config['dsn']);
if ($factoryClass = $this->findFactoryClass($dsn, Resources::getAvailableConnections())) {
return new $factoryClass(1 === count($config) ? $config['dsn'] : $config);
}
$knownConnections = Resources::getKnownConnections();
if ($factoryClass = $this->findFactoryClass($dsn, $knownConnections)) {
throw new \LogicException(sprintf(
'To use given scheme "%s" a package has to be installed. Run "composer req %s" to add it.',
$dsn->getScheme(),
$knownConnections[$factoryClass]['package']
));
}
throw new \LogicException(sprintf(
'A given scheme "%s" is not supported. Maybe it is a custom connection, make sure you registered it with "%s::addConnection".',
$dsn->getScheme(),
Resources::class
));
}
private function findFactoryClass(Dsn $dsn, array $factories): ?string
{
$protocol = $dsn->getSchemeProtocol();
if ($dsn->getSchemeExtensions()) {
foreach ($factories as $connectionClass => $info) {
if (empty($info['supportedSchemeExtensions'])) {
continue;
}
if (false == in_array($protocol, $info['schemes'], true)) {
continue;
}
$diff = array_diff($info['supportedSchemeExtensions'], $dsn->getSchemeExtensions());
if (empty($diff)) {
return $connectionClass;
}
}
}
foreach ($factories as $driverClass => $info) {
if (false == in_array($protocol, $info['schemes'], true)) {
continue;
}
return $driverClass;
}
return null;
}
}