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 7d5200b
Showing 1 changed file with 41 additions and 13 deletions.
54 changes: 41 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,48 @@ 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__,
[false],
sortedByKey: $sortedByTime,
);
}

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

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

return $memoryUsages;
return $expandedRecords;
}
}

0 comments on commit 7d5200b

Please sign in to comment.