diff --git a/src/Profile.php b/src/Profile.php index 6bd2cd6..44464b7 100644 --- a/src/Profile.php +++ b/src/Profile.php @@ -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; @@ -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 $myRecords + * @param array $myChildren + * @param array $args + * + * @return array + */ + 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; } }