From eddb1a3540948bcd79638a1524dce40bc60cb34f Mon Sep 17 00:00:00 2001 From: Pascal Baljet Date: Fri, 13 May 2022 09:43:48 +0200 Subject: [PATCH] Bugfix for negative file sizes. --- CHANGELOG.md | 4 ++++ src/String/HumanFilesize.php | 6 +++++- tests/String/HumanFilesizeTest.php | 1 + 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 124d53e..0e2a3ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ All notable changes to `laravel-mixins` will be documented in this file. +## 3.3.1 - 2022-05-13 + +- Bugfix for negative file sizes. + ## 3.3.0 - 2022-02-22 - Added `SecondsToTime` string macro. diff --git a/src/String/HumanFilesize.php b/src/String/HumanFilesize.php index 82a6b5a..d5b7f72 100644 --- a/src/String/HumanFilesize.php +++ b/src/String/HumanFilesize.php @@ -15,6 +15,10 @@ public function humanFilesize(): callable * Formats the $value into a human readable filesize. */ return function ($value, $precision = 1): string { + $isNegative = $value < 0; + + $value = abs($value); + if ($value >= 1000000000000) { $value = round($value / (1024 * 1024 * 1024 * 1024), $precision); $unit = 'TB'; @@ -32,7 +36,7 @@ public function humanFilesize(): callable return number_format($value) . ' ' . $unit; } - return number_format($value, $precision) . ' ' . $unit; + return ($isNegative ? '-' : '') . number_format($value, $precision) . ' ' . $unit; }; } } diff --git a/tests/String/HumanFilesizeTest.php b/tests/String/HumanFilesizeTest.php index e42f27a..cb9ef3b 100644 --- a/tests/String/HumanFilesizeTest.php +++ b/tests/String/HumanFilesizeTest.php @@ -25,6 +25,7 @@ public function it_can_format_file_size() $this->assertEquals('44.6 KB', Str::humanFilesize(45678)); $this->assertEquals('446.1 KB', Str::humanFilesize(456789)); $this->assertEquals('3.3 MB', Str::humanFilesize(3456789)); + $this->assertEquals('-3.3 MB', Str::humanFilesize(-3456789)); $this->assertEquals('1.8 GB', Str::humanFilesize(1932735283.2)); $this->assertEquals('112,283.3 TB', Str::humanFilesize(123456789123456789)); }