From 541faa5f82ff1d5396d065de03e4563d94465c22 Mon Sep 17 00:00:00 2001 From: Artem Stepanenko Date: Sat, 27 Aug 2022 11:13:35 +0300 Subject: [PATCH] readableMemory to formatMemory --- src/helpers.php | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/helpers.php b/src/helpers.php index 3adf876..95f067f 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -23,27 +23,23 @@ function rglob($pattern) } } -if (!function_exists('readableMemory')) { - /** - * readableMemory - * - * @param mixed $memory - * @param bool $startFromBytes - * @param bool $withUnit - * @return mixed - */ - function readableMemory($memory, $startFromBytes = false, $withUnit = true) +if (!function_exists('formatMemory')) { + function formatMemory(float $size, int $level = 0, int $precision = 2, int $base = 1024, $asArray = false): string { - $i = floor(log($memory) / log(1024)); - $sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - if ($startFromBytes) array_unshift($sizes, 'B'); - - if ($withUnit) - return sprintf('%.02F', $memory / pow(1024, $i)) * 1 . ' ' . $sizes[$i]; - else return [ - 'memory' => sprintf('%.02F', $memory / pow(1024, $i)) * 1, - 'unit' => $sizes[$i], - ]; + $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + $times = floor(log($size, $base)); + + $memory = sprintf('%.' . $precision . 'f', $size / pow($base, ($times + $level))); + $unit = $unit[$times + $level]; + + if ($asArray) { + return [ + 'memory' => $memory, + 'unit' => $unit, + ]; + } + + return $memory . ' ' . $unit; } }