Frequency.php 2.0 KB

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