Passed
Pull Request — main (#34)
by Sílvio
02:57
created

CacheStats::recordHit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Utils;
4
5
class CacheStats
6
{
7
    private int $hits = 0;
8
    private int $misses = 0;
9
    private array $readTimes = [];
10
    private array $writeTimes = [];
11
    private ?CacheLogger $logger = null;
12
13
    public function __construct(CacheLogger $logger = null)
14
    {
15
        $this->logger = $logger;
16
    }
17
18
    public function recordHit(float $time): void
19
    {
20
        $this->hits++;
21
        $this->readTimes[] = $time;
22
        if ($this->logger) {
23
            $this->logger->debug("Cache hit in {$time} seconds.");
24
        }
25
    }
26
27
    public function recordMiss(float $time): void
28
    {
29
        $this->misses++;
30
        $this->readTimes[] = $time;
31
        if ($this->logger) {
32
            $this->logger->debug("Cache miss in {$time} seconds.");
33
        }
34
    }
35
36
    public function recordWrite(float $time): void
37
    {
38
        $this->writeTimes[] = $time;
39
        if ($this->logger) {
40
            $this->logger->debug("Cache write in {$time} seconds.");
41
        }
42
    }
43
44
    public function getHitCount(): int
45
    {
46
        return $this->hits;
47
    }
48
49
    public function getMissCount(): int
50
    {
51
        return $this->misses;
52
    }
53
54
    public function getAverageReadTime(): float
55
    {
56
        if (empty($this->readTimes)) {
57
            return 0;
58
        }
59
        return array_sum($this->readTimes) / count($this->readTimes);
60
    }
61
62
    public function getAverageWriteTime(): float
63
    {
64
        if (empty($this->writeTimes)) {
65
            return 0;
66
        }
67
        return array_sum($this->writeTimes) / count($this->writeTimes);
68
    }
69
}
70