|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace RemotelyLiving\PHPQueryBus\DTO\Cache; |
|
6
|
|
|
|
|
7
|
|
|
use RemotelyLiving\PHPQueryBus\AbstractResult; |
|
8
|
|
|
use RemotelyLiving\PHPQueryBus\Exceptions\UnserializationFailure; |
|
9
|
|
|
use RemotelyLiving\PHPQueryBus\Interfaces; |
|
10
|
|
|
use RemotelyLiving\PHPQueryBus\Traits; |
|
11
|
|
|
|
|
12
|
|
|
final class ResultWrapper implements \Serializable |
|
13
|
|
|
{ |
|
14
|
|
|
use Traits\TimeBoundary; |
|
15
|
|
|
|
|
16
|
|
|
private Interfaces\Result $result; |
|
17
|
|
|
|
|
18
|
|
|
private float $recomputeSeconds; |
|
19
|
|
|
|
|
20
|
|
|
private int $ttl; |
|
21
|
|
|
|
|
22
|
|
|
private float $storedTimestamp; |
|
23
|
|
|
|
|
24
|
|
|
private function __construct() |
|
25
|
|
|
{ |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public static function wrap(Interfaces\Result $result, float $recomputeSeconds, int $ttl): self |
|
29
|
|
|
{ |
|
30
|
|
|
$self = new self(); |
|
31
|
|
|
$self->result = $result; |
|
32
|
|
|
$self->recomputeSeconds = $recomputeSeconds; |
|
33
|
|
|
$self->ttl = $ttl; |
|
34
|
|
|
|
|
35
|
|
|
return $self; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function serialize(): string |
|
39
|
|
|
{ |
|
40
|
|
|
return \serialize([ |
|
41
|
|
|
'result' => $this->result, |
|
42
|
|
|
'recomputeSeconds' => $this->recomputeSeconds, |
|
43
|
|
|
'ttl' => $this->ttl, |
|
44
|
|
|
'storedTimestamp' => $this->getTimeStamp(), |
|
45
|
|
|
]); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @psalm-suppress PropertyTypeCoercion |
|
50
|
|
|
* @phpstan-ignore-next-line |
|
51
|
|
|
*/ |
|
52
|
|
|
public function unserialize($serialized, array $options = null): void |
|
53
|
|
|
{ |
|
54
|
|
|
$unserialized = (!$options) ? \unserialize($serialized) : \unserialize($serialized, $options); |
|
55
|
|
|
$this->result = (is_object($unserialized['result']) && $unserialized['result'] instanceof Interfaces\Result) |
|
56
|
|
|
? $unserialized['result'] |
|
57
|
|
|
: AbstractResult::withErrors(new UnserializationFailure('Result object failed to unserialize properly')); |
|
58
|
|
|
$this->recomputeSeconds = $unserialized['recomputeSeconds']; |
|
59
|
|
|
$this->ttl = $unserialized['ttl']; |
|
60
|
|
|
$this->storedTimestamp = $unserialized['storedTimestamp']; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public function getResult(): Interfaces\Result |
|
64
|
|
|
{ |
|
65
|
|
|
return $this->result; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function willProbablyExpireSoon(): bool |
|
69
|
|
|
{ |
|
70
|
|
|
return ($this->getTimeStamp() - $this->recomputeSeconds * 1 * log(mt_rand() / mt_getrandmax()) |
|
71
|
|
|
> $this->expiresAfterTimestamp()); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
private function expiresAfterTimestamp(): int |
|
75
|
|
|
{ |
|
76
|
|
|
return (int) (($this->storedTimestamp ?? $this->getTimeStamp()) + $this->ttl); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|