PerfBudgetLogger   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 42
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isOverThresholds() 0 3 2
A __construct() 0 8 1
A __invoke() 0 17 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RemotelyLiving\PHPQueryBus\Middleware;
6
7
use Psr\Log;
8
use RemotelyLiving\PHPQueryBus\Interfaces;
9
use RemotelyLiving\PHPQueryBus\Enums;
10
use RemotelyLiving\PHPQueryBus\Traits;
11
12
final class PerfBudgetLogger implements Log\LoggerAwareInterface
13
{
14
    use Traits\Logger;
15
16
    private int $thresholdSeconds;
17
18
    private float $thresholdMemoryMB;
19
20
    private Enums\LogLevel $logLevel;
21
22
    public function __construct(
23
        int $thresholdSeconds = 10,
24
        float $thresholdMemoryMB = 10.0,
25
        Enums\LogLevel $logLevel = null
26
    ) {
27
        $this->thresholdSeconds = $thresholdSeconds;
28
        $this->thresholdMemoryMB = $thresholdMemoryMB;
29
        $this->logLevel = $logLevel ?? Enums\LogLevel::WARNING();
30
    }
31
32
    public function __invoke(object $query, callable $next): Interfaces\Result
33
    {
34
        $startTime = microtime(true);
35
        $startMemoryBytes = memory_get_usage(true);
36
        $result = $next($query);
37
        $totalTime = (float) microtime(true) - $startTime;
38
        $totalMegabytesIncrease = (memory_get_peak_usage(true) - $startMemoryBytes) / 1000000;
39
40
        if ($this->isOverThresholds($totalTime, $totalMegabytesIncrease)) {
41
            $this->getLogger()->log(
42
                (string) $this->logLevel,
43
                'Performance threshold exceeded',
44
                ['MB' => $totalMegabytesIncrease, 'seconds' => $totalTime, 'query' => get_class($query) ]
45
            );
46
        }
47
48
        return $result;
49
    }
50
51
    private function isOverThresholds(float $seconds, float $megaBytes): bool
52
    {
53
        return ($seconds > $this->thresholdSeconds || ($megaBytes) > $this->thresholdMemoryMB);
54
    }
55
}
56