MeasureMiddleware::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 13
cts 13
cp 1
rs 9.568
c 0
b 0
f 0
cc 4
nc 1
nop 2
crap 4
1
<?php declare(strict_types=1);
2
3
namespace WyriHaximus\React\Http\Middleware;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use function React\Promise\resolve;
7
8
final class MeasureMiddleware
9
{
10
    /** @var int */
11
    private $current = 0;
12
13
    /** @var int */
14
    private $total = 0;
15
16
    /** @var null|float */
17
    private $tookMin = null;
18
19
    /** @var float */
20
    private $tookMax = 0.0;
21
22
    /** @var float */
23
    private $tookAvg = 0.0;
24
25
    /** @var float */
26
    private $tookTotal = 0.0;
27
28 1
    public function __invoke(ServerRequestInterface $request, callable $next)
29
    {
30 1
        $this->current++;
31 1
        $start = \microtime(true);
32
33
        return resolve($next($request))->always(function () use ($start): void {
34 1
            $took = \microtime(true) - $start;
35 1
            $this->current--;
36 1
            $this->total++;
37 1
            $this->tookTotal += $took;
38
39 1
            if ($this->tookMin === null || $took < $this->tookMin) {
40 1
                $this->tookMin = $took;
41
            }
42
43 1
            if ($this->tookMax < $took) {
44 1
                $this->tookMax = $took;
45
            }
46
47 1
            $this->tookAvg = $this->tookTotal / $this->total;
48 1
        });
49
    }
50
51 1
    public function collect(): iterable
52
    {
53 1
        yield 'current' => $this->current;
54 1
        yield 'total' => $this->total;
55 1
        yield 'took.min' => $this->tookMin === null ? 0.0 : $this->tookMin;
56 1
        yield 'took.max' => $this->tookMax;
57 1
        yield 'took.average' => $this->tookAvg;
58 1
        yield 'took.total' => $this->tookTotal;
59
60 1
        $this->total = 0;
61 1
        $this->tookMin = null;
62 1
        $this->tookMax = 0.0;
63 1
        $this->tookAvg = 0.0;
64 1
        $this->tookTotal = 0;
0 ignored issues
show
Documentation Bug introduced by
The property $tookTotal was declared of type double, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
65 1
    }
66
67
    public function cancel(): void
68
    {
69
        // Does not apply to this class
70
    }
71
}
72