Skip to content

Commit

Permalink
Support negative byte values in FS::format method (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
SmetDenis authored Mar 28, 2024
1 parent 4630245 commit bfea6b6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/FS.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/FileSystemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);

Expand Down

0 comments on commit bfea6b6

Please sign in to comment.