From be8aa2fd30d3fe8269e01ea3b03f05fd0ecfcc99 Mon Sep 17 00:00:00 2001 From: Petr Knap <8299754+petrknap@users.noreply.github.com> Date: Sun, 13 Oct 2024 09:16:25 +0200 Subject: [PATCH] refactor: unified way how to expand records in profile --- src/Profile.php | 47 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/src/Profile.php b/src/Profile.php index 6bd2cd6..a03b5da 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,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 $myRecords + * @param array $myChildren + * + * @return array + */ + 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; } }