Skip to content

Commit

Permalink
Fix DivisionByZeroError in File::getHumanReadable() (#3549)
Browse files Browse the repository at this point in the history
* Fix DivisionByZeroError

* Use triple equal

* Change back to double equals comparison

* test for 0 bytes
  • Loading branch information
ziming authored Feb 20, 2024
1 parent 1d56eac commit 899d7f6
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Support/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ public static function getHumanReadableSize(int|float $sizeInBytes): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

// 0 === 0.00 return false so use double equals
if ($sizeInBytes == 0) {
return '0 '.$units[0];
}

$index = min(count($units) - 1, floor(log(abs($sizeInBytes), 1024)));

return sprintf('%s %s', round(num: abs($sizeInBytes) / (1024 ** $index), precision: 2), $units[$index]);
Expand Down
1 change: 1 addition & 0 deletions tests/Support/FileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use Spatie\MediaLibrary\Support\File;

it('can determine a human readable filesize', function () {
expect(File::getHumanReadableSize(0))->toEqual('0 B');
expect(File::getHumanReadableSize(10))->toEqual('10 B');
expect(File::getHumanReadableSize(100))->toEqual('100 B');
expect(File::getHumanReadableSize(1000))->toEqual('1000 B');
Expand Down

0 comments on commit 899d7f6

Please sign in to comment.