From fb0e6ce4cf13ee7f51c31c1b764cc7e639481b73 Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Sat, 28 Oct 2023 10:44:46 +0200 Subject: [PATCH] Add a `Number::bytesToHuman()` helper Ports https://github.com/laravel/framework/pull/48827 into the new `Number` utility class --- src/Illuminate/Support/Number.php | 18 +++++++++++++++++- tests/Support/SupportNumberTest.php | 16 +++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Support/Number.php b/src/Illuminate/Support/Number.php index 88ebd5443510..670dbc68f141 100644 --- a/src/Illuminate/Support/Number.php +++ b/src/Illuminate/Support/Number.php @@ -8,5 +8,21 @@ class Number { use Macroable; - // + /** + * Format the number of bytes to a human-readable string. + * + * @param int $bytes + * @param int $precision + * @return string + */ + public static function bytesToHuman($bytes, $precision = 2) + { + $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + + for ($i = 0; ($bytes / 1024) > 0.9 && ($i < count($units) - 1); $i++) { + $bytes /= 1024; + } + + return sprintf('%s %s', round($bytes, $precision), $units[$i]); + } } diff --git a/tests/Support/SupportNumberTest.php b/tests/Support/SupportNumberTest.php index 805945a08887..ab413275e38a 100644 --- a/tests/Support/SupportNumberTest.php +++ b/tests/Support/SupportNumberTest.php @@ -7,5 +7,19 @@ class SupportNumberTest extends TestCase { - // + public function testBytesToHuman() + { + $this->assertSame('0 B', Number::bytesToHuman(0)); + $this->assertSame('1 B', Number::bytesToHuman(1)); + $this->assertSame('1 KB', Number::bytesToHuman(1024)); + $this->assertSame('2 KB', Number::bytesToHuman(2048)); + $this->assertSame('1.23 KB', Number::bytesToHuman(1264)); + $this->assertSame('1.234 KB', Number::bytesToHuman(1264, 3)); + $this->assertSame('5 GB', Number::bytesToHuman(1024 * 1024 * 1024 * 5)); + $this->assertSame('10 TB', Number::bytesToHuman((1024 ** 4) * 10)); + $this->assertSame('10 PB', Number::bytesToHuman((1024 ** 5) * 10)); + $this->assertSame('1 ZB', Number::bytesToHuman(1024 ** 7)); + $this->assertSame('1 YB', Number::bytesToHuman(1024 ** 8)); + $this->assertSame('1024 YB', Number::bytesToHuman(1024 ** 9)); + } }