From 830e71f75120b877875b50c1acd56d34e64df470 Mon Sep 17 00:00:00 2001 From: Ben Walch Date: Wed, 6 Sep 2023 15:21:58 +0200 Subject: [PATCH] fix human-readable filesize (#204) (#206) --- src/Service/DownloadInfoService.php | 28 ++++++++++-------------- tests/UnitDefault/Areas/DownloadTest.php | 4 ++-- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/Service/DownloadInfoService.php b/src/Service/DownloadInfoService.php index 07ee79cb..ce0c97aa 100644 --- a/src/Service/DownloadInfoService.php +++ b/src/Service/DownloadInfoService.php @@ -90,23 +90,17 @@ public function getDownloadInfo( public function getOptimizedFileSize(mixed $bytes, int $precision): string { - if ($bytes >= 1073741824) { - $bytes = number_format($bytes / 1073741824, 2); - $format = 'gb'; - } elseif ($bytes >= 1048576) { - $bytes = number_format($bytes / 1048576, 2); - $format = 'mb'; - } elseif ($bytes >= 1024) { - $bytes = number_format($bytes / 1024, 2); - $format = 'kb'; - } elseif ($bytes > 1) { - $format = 'bytes'; - } elseif ($bytes === 1) { - $format = 'byte'; - } else { - $format = 'bytes'; + if ($bytes === 1) { + return '1 Byte'; } - - return round((float) $bytes, $precision) . ' ' . $format; + // https://gist.github.com/liunian/9338301?permalink_comment_id=1804497#gistcomment-1804497 + static $units = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + $step = 1024; + $i = 0; + while (($bytes / $step) > 0.9) { + $bytes = $bytes / $step; + $i++; + } + return round($bytes, $precision) . ' ' . ($units[$i] ?? ''); } } diff --git a/tests/UnitDefault/Areas/DownloadTest.php b/tests/UnitDefault/Areas/DownloadTest.php index ed57d2f3..8c274dd9 100644 --- a/tests/UnitDefault/Areas/DownloadTest.php +++ b/tests/UnitDefault/Areas/DownloadTest.php @@ -206,13 +206,13 @@ private function getCompareWithFileInfo($path1, $path2)
  • Download - (jpg, 337 kb) + (jpg, 337 kB)
  • Download - (jpg, 337 kb) + (jpg, 337 kB)