-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPredisClient.php
More file actions
75 lines (64 loc) · 1.93 KB
/
PredisClient.php
File metadata and controls
75 lines (64 loc) · 1.93 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
<?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 Koded\Caching\Cache;
use Koded\Stdlib\Serializer;
use function Koded\Caching\verify_key;
/**
* Class PredisClient uses the Predis library.
*
* @property \Predis\Client client
*/
final class PredisClient implements Cache
{
use ClientTrait, MultiplesTrait;
private Serializer $serializer;
public function __construct(\Predis\Client $client, Serializer $serializer, null|int $ttl = null)
{
$this->client = $client;
$this->serializer = $serializer;
$this->ttl = $ttl;
}
public function get(string $key, mixed $default = null): mixed
{
return $this->has($key)
? $this->serializer->unserialize($this->client->get($key))
: $default;
}
public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
{
verify_key($key);
$expiration = $this->secondsWithGlobalTtl($ttl);
if (null === $ttl && 0 === $expiration) {
return 'OK' === $this->client->set($key, $this->serializer->serialize($value))->getPayload();
}
if ($expiration > 0) {
return 'OK' === $this->client->setex($key, $expiration, $this->serializer->serialize($value))->getPayload();
}
$this->client->del($key);
return true;
}
public function delete(string $key): bool
{
if (false === $this->has($key)) {
return true;
}
return 1 === $this->client->del($key);
}
public function clear(): bool
{
return 'OK' === $this->client->flushdb()->getPayload();
}
public function has(string $key): bool
{
verify_key($key);
return 1 === $this->client->exists($key);
}
}