-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClientFactory.php
More file actions
160 lines (145 loc) · 5.74 KB
/
ClientFactory.php
File metadata and controls
160 lines (145 loc) · 5.74 KB
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
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <mihail@kodeart.com>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*/
namespace Koded\Caching\Client;
use Exception;
use Koded\Caching\{Cache, CacheException};
use Memcached;
use Koded\Caching\Configuration\{MemcachedConfiguration, PredisConfiguration, RedisConfiguration};
use Koded\Stdlib\{Configuration, Serializer};
use Koded\Stdlib\Serializer\SerializerFactory;
use Psr\Log\{LoggerInterface, NullLogger};
use Redis;
use Throwable;
use function error_log;
use function getenv;
use function sprintf;
use function strtolower;
final class ClientFactory
{
public const CACHE_CLIENT = 'CACHE_CLIENT';
public function __construct(private Configuration $factory) {}
/**
* Create an instance of specific cache client.
*
* @param string $client The required cache client
* (memcached, redis, predis, shmop, file, memory)
*
* @return Cache An instance of the cache client
* @throws CacheException
* @throws Exception
*/
public function new(string $client = ''): Cache
{
$client = strtolower($client ?: getenv(self::CACHE_CLIENT) ?: 'memory');
$config = $this->factory->build($client);
return match ($client) {
'memory' => new MemoryClient($config->get('ttl')),
'memcached' => $this->createMemcachedClient($config),
'redis' => $this->createRedisClient($config),
'predis' => $this->createPredisClient($config),
'shmop' => new ShmopClient((string)$config->get('dir'), $config->get('ttl')),
'file' => new FileClient($this->getLogger($config), (string)$config->get('dir'), $config->get('ttl')),
default => throw CacheException::forUnsupportedClient($client)
};
}
private function createMemcachedClient(MemcachedConfiguration|Configuration $conf): Cache
{
$client = new Memcached($conf->get('id'));
$client->setOptions($conf->getOptions());
if (empty($client->getServerList())) {
$client->addServers($conf->getServers());
}
return new MemcachedClient($client, $conf->getTtl());
}
private function createRedisClient(RedisConfiguration|Configuration $conf): Cache
{
$serializer = $conf->get('serializer');
$binary = $conf->get('binary');
if (Serializer::JSON === $serializer && $binary) {
return new RedisJsonClient(
$this->newRedisClient($conf),
SerializerFactory::new((string)$binary, ...$conf->get('options', [0])),
(int)$conf->get('options'),
$conf->get('ttl')
);
}
return new RedisClient(
$this->newRedisClient($conf),
SerializerFactory::new($serializer, ...$conf->get('options', [0])),
$conf->get('ttl')
);
}
private function createPredisClient(PredisConfiguration|Configuration $conf): Cache
{
$binary = $conf->get('binary');
if (Serializer::JSON === $conf->get('serializer') && $binary) {
return new PredisJsonClient(
$this->newPredisClient($conf),
SerializerFactory::new((string)$binary, ...$conf->get('options', [0])),
(int)$conf->get('options'),
$conf->get('ttl')
);
}
return new PredisClient(
$this->newPredisClient($conf),
SerializerFactory::new($conf->get('serializer'), ...$conf->get('options', [0])),
$conf->get('ttl')
);
}
private function newRedisClient(RedisConfiguration $conf): Redis
{
$client = new Redis;
try {
@$client->connect(...$conf->getConnectionParams());
$client->setOption(Redis::OPT_SERIALIZER, $conf->get('type'));
$client->setOption(Redis::OPT_PREFIX, $conf->get('prefix'));
$client->select((int)$conf->get('db'));
if ($auth = $conf->get('auth')) {
$client->auth($auth);
}
if ($message = $client->getLastError()) {
// [NOTE] Redis module complains if auth is set,
// but <Redis v5 or less> does not have auth
throw new Exception($message);
}
return $client;
} /** @noinspection PhpRedundantCatchClauseInspection */
catch (Throwable $e) {
error_log(sprintf(PHP_EOL . '[Redis] %s: %s', $e::class, $e->getMessage()));
error_log('[Redis] with conf: ' . $conf->delete('auth')->toJSON());
throw CacheException::withConnectionErrorFor('Redis');
}
}
private function newPredisClient(PredisConfiguration $conf): \Predis\Client
{
$client = new \Predis\Client($conf->getConnectionParams(), $conf->getOptions());
try {
$client->connect();
$client->select((int)$conf->get('db'));
if ($auth = $conf->get('auth')) {
$client->auth($auth);
}
return $client;
} /** @noinspection PhpRedundantCatchClauseInspection */
catch (Throwable $e) {
error_log(sprintf(PHP_EOL . '[Predis] %s: %s', $e::class, $e->getMessage()));
error_log('[Predis] with conf: ' . $conf->delete('auth')->toJSON());
throw CacheException::withConnectionErrorFor('Predis');
}
}
private function getLogger(Configuration $conf): LoggerInterface
{
$logger = $conf->logger ?? new NullLogger;
if ($logger instanceof LoggerInterface) {
return $logger;
}
throw CacheException::forUnsupportedLogger(LoggerInterface::class, $logger::class);
}
}