From bfea6b63961aae711ec05d5522abf6736f314bb7 Mon Sep 17 00:00:00 2001 From: Denis Smetannikov Date: Thu, 28 Mar 2024 20:37:27 +0400 Subject: [PATCH] Support negative byte values in FS::format method (#50) --- src/FS.php | 15 ++++++--------- tests/FileSystemTest.php | 12 ++++++++++++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/FS.php b/src/FS.php index fb3be42..2313dff 100644 --- a/src/FS.php +++ b/src/FS.php @@ -284,22 +284,19 @@ public static function ls(string $dir): array */ public static function format(int $bytes, int $decimals = 2): string { - $exp = 0; - $value = 0; - $symbols = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + $isNegative = $bytes < 0; - $bytes = (float)$bytes; + $symbols = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - if ($bytes > 0) { - $exp = (int)\floor(\log($bytes) / \log(1024)); - $value = ($bytes / (1024 ** \floor($exp))); - } + $bytes = \abs((float)$bytes); + $exp = (int)\floor(\log($bytes) / \log(1024)); + $value = ($bytes / (1024 ** \floor($exp))); if ($symbols[$exp] === 'B') { $decimals = 0; } - return \number_format($value, $decimals, '.', '') . ' ' . $symbols[$exp]; + return ($isNegative ? '-' : '') . \number_format($value, $decimals, '.', '') . ' ' . $symbols[$exp]; } /** diff --git a/tests/FileSystemTest.php b/tests/FileSystemTest.php index 0d264b5..80d7809 100644 --- a/tests/FileSystemTest.php +++ b/tests/FileSystemTest.php @@ -284,9 +284,18 @@ public function testLS(): void public function testFormat(): void { + $size = FS::format(0); + is('0 B', $size); + + $size = FS::format(0, 0); + is('0 B', $size); + $size = FS::format(512, 0); is('512 B', $size); + $size = FS::format(-512, 0); + is('-512 B', $size); + $size = FS::format(512); is('512 B', $size); @@ -299,6 +308,9 @@ public function testFormat(): void $size = FS::format(19971597926); is('18.60 GB', $size); + $size = FS::format(-19971597926); + is('-18.60 GB', $size); + $size = FS::format(2748779069440, 1); is('2.5 TB', $size);