diff --git a/src/Exception/ProfilerCouldNotSnapshotOutsideProfile.php b/src/Exception/ProfilerCouldNotSnapshotOutsideProfile.php new file mode 100644 index 0000000..dfffbc2 --- /dev/null +++ b/src/Exception/ProfilerCouldNotSnapshotOutsideProfile.php @@ -0,0 +1,11 @@ + & ProfileWithOutputInterface */ public function profile(callable $callable): ProcessableProfileInterface & ProfileWithOutputInterface; + + /** + * @throws Exception\ProfilerCouldNotSnapshotOutsideProfile + */ + public function snapshot(): void; } diff --git a/src/Profiling.php b/src/Profiling.php index 6e83064..f8808b0 100644 --- a/src/Profiling.php +++ b/src/Profiling.php @@ -88,6 +88,14 @@ public function profile(callable $callable): ProcessableProfileInterface & Profi $this->parentProfile->registerTickSnapshot(); } } + + public function snapshot(): void + { + if ($this->parentProfile->getState() !== ProfileState::Started) { + throw new Exception\ProfilerCouldNotSnapshotOutsideProfile(); + } + $this->parentProfile->snapshot(); + } }; } diff --git a/tests/NullProfilerTest.php b/tests/NullProfilerTest.php index 035bed9..80eaff1 100644 --- a/tests/NullProfilerTest.php +++ b/tests/NullProfilerTest.php @@ -41,4 +41,13 @@ public function testProfileDoesNotRunProcessorAndReturnsCallablesOutput(): void self::assertFalse($processorWasCalled); self::assertSame('output', $output); } + + public function testSnapshotDoNotThrow(): void + { + $profiler = new NullProfiler(); + + $profiler->snapshot(); + + self::assertTrue(true); + } } diff --git a/tests/ProfilerTest.php b/tests/ProfilerTest.php index 168eaf4..30110e8 100644 --- a/tests/ProfilerTest.php +++ b/tests/ProfilerTest.php @@ -37,4 +37,22 @@ public function testReturnsCallablesOutput(): void self::assertSame('output', $profile->getOutput()); } + + public function testSnapshotsOnParentProfile(): void + { + $profiler = new Profiler(); + + $profile = $profiler->profile(static fn (ProfilerInterface $profiler) => $profiler->snapshot()); + + self::assertCount(3, $profile->getMemoryUsages()); + } + + public function testSnapshotsThrowsOutsideProfile(): void + { + $profiler = new Profiler(); + + self::expectException(Exception\ProfilerCouldNotSnapshotOutsideProfile::class); + + $profiler->snapshot(); + } }