-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Profiling.php
109 lines (93 loc) · 3.1 KB
/
Profiling.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
namespace PetrKnap\Profiler;
final class Profiling
{
/**
* @param Profile<mixed> $profile
*/
private function __construct(
private readonly Profile $profile,
private readonly bool $takeSnapshotOnTick,
) {
}
public static function start(
bool $takeSnapshotOnTick = Profile::DO_NOT_TAKE_SNAPSHOT_ON_TICK,
/**
* @deprecated backward compatibility with old named argument calls
*
* @todo remove it
*/
bool $listenToTicks = Profile::DO_NOT_TAKE_SNAPSHOT_ON_TICK,
): self {
$profile = new Profile($listenToTicks || $takeSnapshotOnTick);
$profile->start();
return new self($profile, $listenToTicks || $takeSnapshotOnTick);
}
/**
* @throws Exception\ProfilingHasBeenAlreadyFinished
*/
public function takeSnapshot(): void
{
$this->checkProfileState();
$this->profile->takeSnapshot();
}
/**
* @throws Exception\ProfilingHasBeenAlreadyFinished
*/
public function finish(): ProfileInterface
{
$this->checkProfileState();
$this->profile->finish();
return $this->profile;
}
/**
* @internal should be used only by {@see Profiler::profile()}
*/
public static function createNestedProfiler(Profiling $profiling): ProfilerInterface
{
return new class ($profiling->profile, $profiling->takeSnapshotOnTick) extends Profiler {
/**
* @param Profile<mixed> $parentProfile
*/
public function __construct(
private readonly Profile $parentProfile,
bool $takeSnapshotOnTick,
) {
parent::__construct(
takeSnapshotOnTick: $takeSnapshotOnTick,
);
}
public function profile(callable $callable): ProcessableProfileInterface & ProfileWithOutputInterface
{
if ($this->parentProfile->getState() !== ProfileState::Started) {
throw new Exception\ParentProfileIsNotStarted();
}
$this->parentProfile->unregisterTickHandlers();
try {
$profile = parent::profile($callable);
$this->parentProfile->addChild($profile);
return $profile;
} finally {
$this->parentProfile->registerTickHandlers();
}
}
public function takeSnapshot(): void
{
if ($this->parentProfile->getState() !== ProfileState::Started) {
throw new Exception\ProfilerCouldNotTakeSnapshotOutsideParentProfile();
}
$this->parentProfile->takeSnapshot();
}
};
}
/**
* @throws Exception\ProfilingHasBeenAlreadyFinished
*/
private function checkProfileState(): void
{
if ($this->profile->getState() === ProfileState::Finished) {
throw new Exception\ProfilingHasBeenAlreadyFinished();
}
}
}