Test Failed
Pull Request — master (#74)
by Evgeniy
01:54
created

CacheItem::expired()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 12
c 2
b 0
f 1
dl 0
loc 22
rs 9.8666
cc 4
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Cache\Metadata;
6
7
use Yiisoft\Cache\Exception\InvalidArgumentException;
8
9
use function ceil;
10
use function log;
11
use function microtime;
12
use function random_int;
13
use function sprintf;
14
use function time;
15
16
use const PHP_INT_MAX;
17
18
final class CacheItem
19
{
20
    private ?int $expiry;
21
    private float $created;
22
23
    public function __construct(?int $expiry)
24
    {
25
        $this->expiry = $expiry;
26
        $this->created = microtime(true);
27
    }
28
29
    public function expiry(?int $expiry): void
30
    {
31
        $this->expiry = $expiry;
32
    }
33
34
    public function expired(float $beta): bool
35
    {
36
        if ($beta < 0) {
37
            throw new InvalidArgumentException(sprintf(
38
                'Argument "$beta" must be a positive number, %f given.',
39
                $beta
40
            ));
41
        }
42
43
        if ($this->expiry === null) {
44
            return false;
45
        }
46
47
        if ($this->expiry <= time()) {
48
            return true;
49
        }
50
51
        $now = microtime(true);
52
        $delta = ceil(1000 * ($now - $this->created)) / 1000;
53
        $expired = $now - $delta * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX);
54
55
        return $this->expiry <= $expired;
56
    }
57
}
58