Benchmarker::getBenchmarks()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Debug;
10
11
use Spiral\Core\Component;
12
use Spiral\Core\Container\SingletonInterface;
13
use Spiral\Debug\Exceptions\BenchmarkException;
14
15
/**
16
 * Generic benchmarker.
17
 *
18
 * @todo improve implementation by returning Benchmark?
19
 */
20
class Benchmarker extends Component implements BenchmarkerInterface, SingletonInterface
21
{
22
    /**
23
     * @invisible
24
     *
25
     * @var array
26
     */
27
    private $benchmarks = [];
28
29
    /**
30
     * {@inheritdoc}
31
     *
32
     * @throws BenchmarkException
33
     */
34 2
    public function benchmark($caller, $record, string $context = '')
35
    {
36 2
        $benchmarkID = count($this->benchmarks);
37 2
        if (is_array($record)) {
38 2
            $benchmarkID = $record[0];
39 1
        } elseif (!isset($this->benchmarks[$benchmarkID])) {
40 1
            $this->benchmarks[$benchmarkID] = [$caller, $record, $context, microtime(true)];
41
42
            //Payload
43 1
            return [$benchmarkID];
44
        }
45
46 2
        if (!isset($this->benchmarks[$benchmarkID])) {
47 1
            throw new BenchmarkException("Unpaired benchmark record '{$benchmarkID}'");
48
        }
49
50 1
        $this->benchmarks[$benchmarkID][4] = microtime(true);
51
52 1
        return $this->benchmarks[$benchmarkID][4] - $this->benchmarks[$benchmarkID][3];
53
    }
54
55
    /**
56
     * Retrieve all active and finished benchmark records.
57
     *
58
     * @return array
59
     */
60 1
    public function getBenchmarks(): array
61
    {
62 1
        return $this->benchmarks;
63
    }
64
}
65