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 is not supported by ApcuStorage,it must be int or float'); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$value = (int) ($value * $this->fixPrecisionRate); |
33
|
|
|
|
34
|
|
|
return 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 is not supported by ApcuStorage,it must be int or float'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ((!is_int($newValue)) && !is_float($newValue)) { |
44
|
|
|
throw new InvalidArgumentException('The newValue is not supported by ApcuStorage,it must be int or float'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$oldValue = (int) ($oldValue * $this->fixPrecisionRate); |
48
|
|
|
$newValue = (int) ($newValue * $this->fixPrecisionRate); |
49
|
|
|
|
50
|
|
|
return apcu_cas($key, $oldValue, $newValue); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function get(string $key): mixed |
54
|
|
|
{ |
55
|
|
|
$value = apcu_fetch($key); |
56
|
|
|
|
57
|
|
|
if ((!is_int($value)) && !is_float($value) && !is_bool($value)) { |
58
|
|
|
throw new InvalidArgumentException('The value is not supported by ApcuStorage,it must be bool, int or float'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if ($value != false) { |
|
|
|
|
62
|
|
|
$value = floatval($value / $this->fixPrecisionRate); |
63
|
|
|
} |
64
|
|
|
return $value; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|