-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMemcachedClient.php
More file actions
93 lines (80 loc) · 2.38 KB
/
Copy pathMemcachedClient.php
File metadata and controls
93 lines (80 loc) · 2.38 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
<?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 Memcached;
use function array_fill_keys;
use function array_replace;
use function Koded\Caching\verify_key;
/**
* @property Memcached client
*/
final class MemcachedClient implements Cache
{
use ClientTrait, MultiplesTrait;
public function __construct(Memcached $client, null|int $ttl = null)
{
$this->ttl = $ttl;
$this->client = $client;
}
public function get(string $key, mixed $default = null): mixed
{
verify_key($key);
// Cannot return get() directly because default value
$value = $this->client->get($key);
return Memcached::RES_SUCCESS === $this->client->getResultCode() ? $value : $default;
}
public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
{
verify_key($key);
$expiration = $this->secondsWithGlobalTtl($ttl);
if (null !== $ttl && $expiration < 1) {
$this->client->delete($key);
return true;
}
return $this->client->set($key, $value, $expiration);
}
public function delete(string $key): bool
{
if (false === $this->has($key)) {
return true;
}
return $this->client->delete($key);
}
public function clear(): bool
{
return $this->client->flush();
}
public function has(string $key): bool
{
verify_key($key);
// Memcached does not have exists() or similar method
$this->client->get($key);
return Memcached::RES_NOTFOUND !== $this->client->getResultCode();
}
/*
*
* Overrides
*
*/
protected function internalMultiGet(array $keys, $default = null): array
{
return array_replace(array_fill_keys($keys, $default), $this->client->getMulti($keys) ?: []);
}
protected function internalMultiSet(array $values, $ttl = null): bool
{
return $this->client->setMulti($values, (int)$ttl);
}
protected function internalMultiDelete(array $keys): bool
{
$this->client->deleteMulti($keys);
return Memcached::RES_FAILURE !== $this->client->getResultCode();
}
}