Test Failed
Pull Request — master (#43)
by
unknown
02:25
created

ApcuStorage::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 4
c 1
b 0
f 1
dl 0
loc 8
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\RateLimiter\Storage;
6
7
use Yiisoft\Yii\RateLimiter\Exception\CannotUseException;
8
9
final class ApcuStorage implements StorageInterface
10
{
11
    private const DEFAULT_FIX_PRECISION_RATE = 1000000;
12
13
    /**
14
     * @param int $fixPrecisionRate 
15
     * floating point is not supported by apcu_cas of ACPu, so use it to improves precision.
16
     */
17
    public function __construct(
18
        private int $fixPrecisionRate = self::DEFAULT_FIX_PRECISION_RATE
19
    ) {
20
        if (!extension_loaded('apcu') || ini_get('apc.enabled') === '0') {
21
            throw new CannotUseException('APCu extension is not loaded or not enabled.');
22
        }
23
    }
24
25
    public function saveIfNotExists(string $key, mixed $value, int $ttl): bool
26
    {
27
        $value = (int) ($value * $this->fixPrecisionRate);
28
        return (bool)apcu_add($key, $value, $ttl);
29
    }
30
31
    public function saveCompareAndSwap(string $key, mixed $oldValue, mixed $newValue, int $ttl): bool
32
    {
33
        $oldValue = (int) ($oldValue * $this->fixPrecisionRate);
34
        $newValue = (int) ($newValue * $this->fixPrecisionRate);
35
        return  (bool)apcu_cas($key, $oldValue, $newValue);
36
    }
37
38
    public function get(string $key): mixed
39
    {
40
        $value = apcu_fetch($key);
41
        
42
        if ($value != false) {
43
            $value = floatval($value / $this->fixPrecisionRate);
44
        }
45
        return $value;
46
    }
47
}
48