Skip to content

Commit

Permalink
feat: added nested profiler factory to profiling helper
Browse files Browse the repository at this point in the history
  • Loading branch information
petrknap committed Oct 11, 2024
1 parent f5fac69 commit 33064c1
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 19 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"profiling",
"profiler",
"profile",
"debugging",
"debug"
],
"license": "LGPL-3.0-or-later",
Expand All @@ -39,7 +40,7 @@
"require-dev": {
"nunomaduro/phpinsights": "^2.11",
"petrknap/shorts": "^2.1",
"phpstan/phpstan": "^1.10",
"phpstan/phpstan": "^1.12",
"phpunit/phpunit": "^10.5",
"squizlabs/php_codesniffer": "^3.7"
},
Expand Down
19 changes: 5 additions & 14 deletions src/Profiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,14 @@

public function profile(callable $callable): ProcessableProfileInterface & ProfileWithOutputInterface
{
$profile = new Profile();

$profile->start();
$output = $callable(new class ($profile) extends Profiler {
/**
* @param Profile<mixed> $parentProfile
*/
public function __construct(Profile $parentProfile)
{
$this->parentProfile = $parentProfile;
}
});
$profile->finish();
$profiling = Profiling::start();
$output = $callable($profiling->createNestedProfiler());
/** @var Profile<mixed> $profile */
$profile = $profiling->finish();
$profile->setOutput($output);

$this->parentProfile?->addChild($profile);

return $profile;
return $profile; // @phpstan-ignore return.type
}
}
26 changes: 22 additions & 4 deletions src/Profiling.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,12 @@

namespace PetrKnap\Profiler;

/**
* @note it is recommended to use {@see ProfilerInterface}
*/
final class Profiling
{
private bool $wasFinished = false;

/**
* @param Profile<void> $profile
* @param Profile<mixed> $profile
*/
private function __construct(
private readonly Profile $profile,
Expand Down Expand Up @@ -41,4 +38,25 @@ public function finish(): ProfileInterface

return $this->profile;
}

/**
* @throws Exception\ProfilingHasBeenAlreadyFinished
*/
public function createNestedProfiler(): ProfilerInterface
{
if ($this->wasFinished) {
throw new Exception\ProfilingHasBeenAlreadyFinished();
}

return new class ($this->profile) extends Profiler {
/**
* @param Profile<mixed> $parentProfile
*/
public function __construct(
Profile $parentProfile,
) {
$this->parentProfile = $parentProfile;
}
};
}
}

0 comments on commit 33064c1

Please sign in to comment.