1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BenTools\MercurePHP\Storage\Redis; |
4
|
|
|
|
5
|
|
|
use BenTools\MercurePHP\Helpers\RedisHelper; |
6
|
|
|
use BenTools\MercurePHP\Storage\StorageFactoryInterface; |
7
|
|
|
use Clue\React\Redis\Client as AsynchronousClient; |
8
|
|
|
use Clue\React\Redis\Factory; |
9
|
|
|
use Predis\Client as SynchronousClient; |
10
|
|
|
use Psr\Log\LoggerInterface; |
11
|
|
|
use React\EventLoop\LoopInterface; |
12
|
|
|
use React\Promise\PromiseInterface; |
13
|
|
|
|
14
|
|
|
use function React\Promise\all; |
15
|
|
|
use function React\Promise\resolve; |
16
|
|
|
|
17
|
|
|
final class RedisStorageFactory implements StorageFactoryInterface |
18
|
|
|
{ |
19
|
|
|
private LoopInterface $loop; |
20
|
|
|
private LoggerInterface $logger; |
21
|
|
|
|
22
|
5 |
|
public function __construct(LoopInterface $loop, LoggerInterface $logger) |
23
|
|
|
{ |
24
|
5 |
|
$this->loop = $loop; |
25
|
5 |
|
$this->logger = $logger; |
26
|
|
|
} |
27
|
4 |
|
|
28
|
|
|
public function supports(string $dsn): bool |
29
|
4 |
|
{ |
30
|
|
|
return RedisHelper::isRedisDSN($dsn); |
31
|
|
|
} |
32
|
1 |
|
|
33
|
|
|
public function create(string $dsn): PromiseInterface |
34
|
1 |
|
{ |
35
|
|
|
$factory = new Factory($this->loop); |
36
|
1 |
|
$promises = [ |
37
|
1 |
|
'async' => $factory->createClient($dsn) |
38
|
|
|
->then( |
39
|
1 |
|
function (AsynchronousClient $client) { |
40
|
1 |
|
$client->on( |
41
|
|
|
'close', |
42
|
|
|
function () { |
43
|
|
|
$this->logger->error('Connection closed.'); |
44
|
1 |
|
$this->loop->stop(); |
45
|
|
|
} |
46
|
|
|
); |
47
|
1 |
|
|
48
|
1 |
|
return $client; |
49
|
|
|
}, |
50
|
|
|
function (\Exception $exception) { |
51
|
|
|
$this->loop->stop(); |
52
|
1 |
|
$this->logger->error($exception->getMessage()); |
53
|
|
|
} |
54
|
1 |
|
), |
55
|
|
|
'sync' => resolve(new SynchronousClient($dsn)), |
56
|
|
|
]; |
57
|
1 |
|
|
58
|
1 |
|
return all($promises) |
59
|
|
|
->then( |
60
|
1 |
|
function (iterable $results): array { |
61
|
1 |
|
$clients = []; |
62
|
1 |
|
foreach ($results as $key => $client) { |
63
|
|
|
$clients[$key] = $client; |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
// Sounds weird, but helps in detecting an anomaly during connection |
67
|
|
|
RedisHelper::testAsynchronousClient($clients['async'], $this->loop, $this->logger); |
68
|
1 |
|
|
69
|
1 |
|
return $clients; |
70
|
|
|
} |
71
|
1 |
|
) |
72
|
1 |
|
->then( |
73
|
1 |
|
fn (array $clients): RedisStorage => new RedisStorage( |
74
|
1 |
|
$clients['async'], |
75
|
|
|
$clients['sync'], |
76
|
1 |
|
) |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|