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

CacheItem::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
nc 1
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
        $this->created = microtime(true);
33
    }
34
35
    public function expired(float $beta): bool
36
    {
37
        if ($beta < 0) {
38
            throw new InvalidArgumentException(sprintf(
39
                'Argument "$beta" must be a positive number, %f given.',
40
                $beta
41
            ));
42
        }
43
44
        if ($this->expiry === null) {
45
            return false;
46
        }
47
48
        if ($this->expiry <= time()) {
49
            return true;
50
        }
51
52
        $now = microtime(true);
53
        $delta = ceil(1000 * ($now - $this->created)) / 1000;
54
        $expired = $now - $delta * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX);
55
56
        return $this->expiry <= $expired;
57
    }
58
}
59