forked from php-enqueue/monitoring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenericStatsStorageFactory.php
65 lines (49 loc) · 1.85 KB
/
GenericStatsStorageFactory.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
<?php
declare(strict_types=1);
namespace Enqueue\Monitoring;
use Enqueue\Dsn\Dsn;
class GenericStatsStorageFactory implements StatsStorageFactory
{
public function create($config): StatsStorage
{
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 ($storageClass = $this->findStorageClass($dsn, Resources::getKnownStorages())) {
return new $storageClass(1 === \count($config) ? $config['dsn'] : $config);
}
throw new \LogicException(sprintf('A given scheme "%s" is not supported.', $dsn->getScheme()));
}
private function findStorageClass(Dsn $dsn, array $factories): ?string
{
$protocol = $dsn->getSchemeProtocol();
if ($dsn->getSchemeExtensions()) {
foreach ($factories as $storageClass => $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 $storageClass;
}
}
}
foreach ($factories as $storageClass => $info) {
if (false === \in_array($protocol, $info['schemes'], true)) {
continue;
}
return $storageClass;
}
return null;
}
}