Skip to content

Commit

Permalink
refactor: unified way how to expand records in profile
Browse files Browse the repository at this point in the history
  • Loading branch information
petrknap committed Oct 13, 2024
1 parent 3ea8a5b commit be8aa2f
Showing 1 changed file with 34 additions and 13 deletions.
47 changes: 34 additions & 13 deletions src/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
final class Profile implements ProcessableProfileInterface, ProfileWithOutputInterface
{
private const MICROTIME_FORMAT = '%.6f';
private const SORTED_BY_TIME = true;

private ProfileState $state;
private OptionalFloat $timeBefore;
Expand Down Expand Up @@ -126,21 +127,41 @@ public function getMemoryUsageChange(): int
return $this->memoryUsageAfter->orElseThrow() - $this->memoryUsageBefore->orElseThrow();
}

public function getMemoryUsages(): array
public function getMemoryUsages(bool $sortedByTime = self::SORTED_BY_TIME): array
{
$memoryUsages = [
sprintf(self::MICROTIME_FORMAT, $this->timeBefore->orElseThrow()) => $this->memoryUsageBefore->orElseThrow(),
sprintf(self::MICROTIME_FORMAT, $this->timeAfter->orElseThrow()) => $this->memoryUsageAfter->orElseThrow(),
];
foreach ($this->children as $child) {
$memoryUsages = array_merge(
$memoryUsages,
$child->getMemoryUsages(),
);
}
return self::expandRecords(
[
sprintf(self::MICROTIME_FORMAT, $this->timeBefore->orElseThrow()) => $this->memoryUsageBefore->orElseThrow(),
sprintf(self::MICROTIME_FORMAT, $this->timeAfter->orElseThrow()) => $this->memoryUsageAfter->orElseThrow(),
],
$this->children,
__FUNCTION__,
sortedByKey: $sortedByTime,
);
}

ksort($memoryUsages);
/**
* @template TRecord of mixed
*
* @param array<numeric-string, TRecord> $myRecords
* @param array<ProfileInterface> $myChildren
*
* @return array<numeric-string, TRecord>
*/
private static function expandRecords(array $myRecords, array $myChildren, string $__function__, bool $sortedByKey = false): array
{
$expandedRecords = array_merge(
$myRecords,
...array_map(
static fn (ProfileInterface $child): array => call_user_func([$child, $__function__], false), // @phpstan-ignore argument.type, return.type
$myChildren,
)
);

if ($sortedByKey) {
ksort($expandedRecords);
}

return $memoryUsages;
return $expandedRecords;
}
}

0 comments on commit be8aa2f

Please sign in to comment.