Skip to content

Commit bfea6b6

Browse files
authored
Support negative byte values in FS::format method (#50)
1 parent 4630245 commit bfea6b6

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

src/FS.php

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -284,22 +284,19 @@ public static function ls(string $dir): array
284284
*/
285285
public static function format(int $bytes, int $decimals = 2): string
286286
{
287-
$exp = 0;
288-
$value = 0;
289-
$symbols = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
287+
$isNegative = $bytes < 0;
290288

291-
$bytes = (float)$bytes;
289+
$symbols = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
292290

293-
if ($bytes > 0) {
294-
$exp = (int)\floor(\log($bytes) / \log(1024));
295-
$value = ($bytes / (1024 ** \floor($exp)));
296-
}
291+
$bytes = \abs((float)$bytes);
292+
$exp = (int)\floor(\log($bytes) / \log(1024));
293+
$value = ($bytes / (1024 ** \floor($exp)));
297294

298295
if ($symbols[$exp] === 'B') {
299296
$decimals = 0;
300297
}
301298

302-
return \number_format($value, $decimals, '.', '') . ' ' . $symbols[$exp];
299+
return ($isNegative ? '-' : '') . \number_format($value, $decimals, '.', '') . ' ' . $symbols[$exp];
303300
}
304301

305302
/**

tests/FileSystemTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,9 +284,18 @@ public function testLS(): void
284284

285285
public function testFormat(): void
286286
{
287+
$size = FS::format(0);
288+
is('0 B', $size);
289+
290+
$size = FS::format(0, 0);
291+
is('0 B', $size);
292+
287293
$size = FS::format(512, 0);
288294
is('512 B', $size);
289295

296+
$size = FS::format(-512, 0);
297+
is('-512 B', $size);
298+
290299
$size = FS::format(512);
291300
is('512 B', $size);
292301

@@ -299,6 +308,9 @@ public function testFormat(): void
299308
$size = FS::format(19971597926);
300309
is('18.60 GB', $size);
301310

311+
$size = FS::format(-19971597926);
312+
is('-18.60 GB', $size);
313+
302314
$size = FS::format(2748779069440, 1);
303315
is('2.5 TB', $size);
304316

0 commit comments

Comments
 (0)