Refreshing::value()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Refreshes manager
4
 * User: moyo
5
 * Date: 24/10/2017
6
 * Time: 12:30 PM
7
 */
8
9
namespace Carno\Cache;
10
11
use function Carno\Coroutine\co;
12
use Carno\Promise\Promised;
13
use Carno\Timer\Timer;
14
use Closure;
15
16
class Refreshing
17
{
18
    /**
19
     * @var array
20
     */
21
    private $timers = [];
22
23
    /**
24
     * @var array
25
     */
26
    private $daemons = [];
27
28
    /**
29
     * @var array
30
     */
31
    private $values = [];
32
33
    /**
34
     * @param string $key
35
     * @param Closure $daemon
36
     * @param int $refreshed
37
     * @return Promised
38
     */
39
    public function register(string $key, Closure $daemon, int $refreshed) : Promised
40
    {
41
        $this->daemons[$key] = $daemon;
42
43
        $refresher = co(function () use ($key) {
44
            $this->values[$key] = yield $this->daemons[$key]();
45
        });
46
47
        $this->timers[$key] = Timer::loop($refreshed * 1000, $refresher);
48
49
        return $refresher();
50
    }
51
52
    /**
53
     */
54
    public function shutdown() : void
55
    {
56
        if (empty($this->timers)) {
57
            return;
58
        }
59
60
        logger('cache')->info('Background refresher is closing', ['timers' => count($this->timers)]);
61
62
        foreach ($this->timers as $timer) {
63
            Timer::clear($timer);
64
        }
65
    }
66
67
    /**
68
     * @param string $key
69
     * @return bool
70
     */
71
    public function has(string $key) : bool
72
    {
73
        return isset($this->values[$key]) || isset($this->timers[$key]);
74
    }
75
76
    /**
77
     * @param string $key
78
     * @return mixed
79
     */
80
    public function value(string $key)
81
    {
82
        return $this->values[$key] ?? yield $this->daemons[$key]();
83
    }
84
}
85