|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\RateLimiter\Storage; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use Yiisoft\Yii\RateLimiter\Exception\CannotUseException; |
|
9
|
|
|
|
|
10
|
|
|
final class ApcuStorage implements StorageInterface |
|
11
|
|
|
{ |
|
12
|
|
|
private const DEFAULT_FIX_PRECISION_RATE = 1000000; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @param int $fixPrecisionRate |
|
16
|
|
|
* floating point is not supported by apcu_cas of ACPu, so use it to improve precision. |
|
17
|
|
|
*/ |
|
18
|
|
|
public function __construct( |
|
19
|
|
|
private int $fixPrecisionRate = self::DEFAULT_FIX_PRECISION_RATE |
|
20
|
|
|
) { |
|
21
|
|
|
if (!extension_loaded('apcu') || ini_get('apc.enabled') === '0') { |
|
22
|
|
|
throw new CannotUseException('APCu extension is not loaded or not enabled.'); |
|
23
|
|
|
} |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function saveIfNotExists(string $key, mixed $value, int $ttl): bool |
|
27
|
|
|
{ |
|
28
|
|
|
if ((!is_int($value)) && !is_float($value)) { |
|
29
|
|
|
throw new InvalidArgumentException('The value must be int or float, is not supported by ApcuStorage'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
$value = (int) ($value * $this->fixPrecisionRate); |
|
33
|
|
|
|
|
34
|
|
|
return (bool)apcu_add($key, $value, $ttl); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function saveCompareAndSwap(string $key, mixed $oldValue, mixed $newValue, int $ttl): bool |
|
38
|
|
|
{ |
|
39
|
|
|
if ((!is_int($oldValue)) && !is_float($oldValue)) { |
|
40
|
|
|
throw new InvalidArgumentException('The oldValue must be int or float, is not supported by ApcuStorage'); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
if ((!is_int($newValue)) && !is_float($newValue)) { |
|
44
|
|
|
throw new InvalidArgumentException('The newValue must be int or float, is not supported by ApcuStorage'); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$oldValue = (int) ($oldValue * $this->fixPrecisionRate); |
|
48
|
|
|
$newValue = (int) ($newValue * $this->fixPrecisionRate); |
|
49
|
|
|
|
|
50
|
|
|
return (bool)apcu_cas($key, $oldValue, $newValue); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function get(string $key): mixed |
|
54
|
|
|
{ |
|
55
|
|
|
$value = apcu_fetch($key); |
|
56
|
|
|
|
|
57
|
|
|
if ($value != false) { |
|
58
|
|
|
$value = floatval($value / $this->fixPrecisionRate); |
|
59
|
|
|
} |
|
60
|
|
|
return $value; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|