Repository navigation
Expand file tree
/
Copy pathFrequency.php
More file actions
92 lines (73 loc) · 2.05 KB
/
Copy pathFrequency.php
File metadata and controls
92 lines (73 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Pool;
use Hyperf\Contract\FrequencyInterface;
class Frequency implements FrequencyInterface, LowFrequencyInterface
{
protected array $hits = [];
/**
* How much time do you want to calculate the frequency ?
*/
protected int $time = 10;
protected int $lowFrequency = 5;
protected int $beginTime;
protected int $lowFrequencyTime;
protected int $lowFrequencyInterval = 60;
public function __construct(protected ?Pool $pool = null)
{
$this->beginTime = time();
$this->lowFrequencyTime = time();
}
public function hit(int $number = 1): bool
{
$this->flush();
$now = time();
$hit = $this->hits[$now] ?? 0;
$this->hits[$now] = $number + $hit;
return true;
}
public function frequency(): float
{
$this->flush();
$hits = 0;
$count = 0;
foreach ($this->hits as $hit) {
++$count;
$hits += $hit;
}
return floatval($hits / $count);
}
public function isLowFrequency(): bool
{
$now = time();
if ($this->lowFrequencyTime + $this->lowFrequencyInterval < $now && $this->frequency() < $this->lowFrequency) {
$this->lowFrequencyTime = $now;
return true;
}
return false;
}
protected function flush(): void
{
$now = time();
$latest = $now - $this->time;
foreach ($this->hits as $time => $hit) {
if ($time < $latest) {
unset($this->hits[$time]);
}
}
if (count($this->hits) < $this->time) {
$beginTime = max($this->beginTime, $latest);
for ($i = $beginTime; $i < $now; ++$i) {
$this->hits[$i] = $this->hits[$i] ?? 0;
}
}
}
}