1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* User: alec |
4
|
|
|
* Date: 14.10.18 |
5
|
|
|
* Time: 2:13 |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace AlecRabbit\Tools; |
9
|
|
|
|
10
|
|
|
use AlecRabbit\Tools\Contracts\ProfilerInterface; |
11
|
|
|
use AlecRabbit\Tools\Reports\Contracts\ReportableInterface; |
12
|
|
|
use AlecRabbit\Tools\Reports\Traits\Reportable; |
13
|
|
|
use AlecRabbit\Traits\DefaultableName; |
14
|
|
|
|
15
|
|
|
class Profiler implements ProfilerInterface, ReportableInterface |
16
|
|
|
{ |
17
|
|
|
use Reportable, DefaultableName; |
18
|
|
|
|
19
|
|
|
/** @var Timer[] */ |
20
|
|
|
private $timers = []; |
21
|
|
|
|
22
|
|
|
/** @var Counter[] */ |
23
|
|
|
private $counters = []; |
24
|
|
|
|
25
|
10 |
|
public function __construct() |
26
|
|
|
{ |
27
|
|
|
// Create "default" counter |
28
|
10 |
|
$this->counter(); |
29
|
|
|
// Create "default" timer |
30
|
10 |
|
$this->timer(); |
31
|
10 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param null|string $name |
35
|
|
|
* @param string ...$suffixes |
36
|
|
|
* @return Counter |
37
|
|
|
*/ |
38
|
10 |
|
public function counter(?string $name = null, string ...$suffixes): Counter |
39
|
|
|
{ |
40
|
10 |
|
$name = $this->prepareName($name, $suffixes); |
41
|
|
|
return |
42
|
10 |
|
$this->counters[$name] ?? $this->counters[$name] = new Counter($name); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param null|string $name |
47
|
|
|
* @param array $suffixes |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
10 |
|
private function prepareName(?string $name, array $suffixes): string |
51
|
|
|
{ |
52
|
10 |
|
$name = $this->defaultName($name); |
53
|
10 |
|
if (!empty($suffixes)) { |
54
|
4 |
|
return $this->formatName($name, $suffixes); |
55
|
|
|
} |
56
|
10 |
|
return $name; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $name |
61
|
|
|
* @param array $suffixes |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
4 |
|
protected function formatName(string $name, array $suffixes): string |
65
|
|
|
{ |
66
|
|
|
return |
67
|
4 |
|
sprintf(static::_NAME_FORMAT, $name, implode(', ', $suffixes)); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param null|string $name |
72
|
|
|
* @param string ...$suffixes |
73
|
|
|
* @return Timer |
74
|
|
|
*/ |
75
|
10 |
|
public function timer(?string $name = null, string ...$suffixes): Timer |
76
|
|
|
{ |
77
|
10 |
|
$name = $this->prepareName($name, $suffixes); |
78
|
|
|
return |
79
|
10 |
|
$this->timers[$name] ?? $this->timers[$name] = new Timer($name); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @return Timer[] |
84
|
|
|
*/ |
85
|
5 |
|
public function getTimers(): array |
86
|
|
|
{ |
87
|
5 |
|
return $this->timers; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* @return Counter[] |
92
|
|
|
*/ |
93
|
5 |
|
public function getCounters(): array |
94
|
|
|
{ |
95
|
5 |
|
return $this->counters; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|