Skip to content

Commit

Permalink
feat(formatter)!: Formatter::filesize() support for robibyte (RiB) …
Browse files Browse the repository at this point in the history
…and quebibyte (QiB). (#106)
  • Loading branch information
LastDragon-ru authored Jan 1, 2024
1 parent a8bec2d commit 56b83fa
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions packages/formatter/defaults/translations/en/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
'EiB' => 'EiB',
'ZiB' => 'ZiB',
'YiB' => 'YiB',
'RiB' => 'RiB',
'QiB' => 'QiB',
],
'disksize' => [
'B' => 'B',
Expand Down
6 changes: 5 additions & 1 deletion packages/formatter/src/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,10 @@ public function datetime(

/**
* Formats number of bytes into units based on powers of 2 (kibibyte, mebibyte, etc).
*
* @param numeric-string|float|int<0, max>|null $bytes
*/
public function filesize(?int $bytes, int $decimals = null): string {
public function filesize(string|float|int|null $bytes, int $decimals = null): string {
return $this->formatFilesize(
$bytes,
$decimals ?: Cast::toInt($this->getOptions(static::Filesize, 2)),
Expand All @@ -359,6 +361,8 @@ public function filesize(?int $bytes, int $decimals = null): string {
$this->getTranslation(['filesize.EiB', 'EiB']),
$this->getTranslation(['filesize.ZiB', 'ZiB']),
$this->getTranslation(['filesize.YiB', 'YiB']),
$this->getTranslation(['filesize.RiB', 'RiB']),
$this->getTranslation(['filesize.QiB', 'QiB']),
],
);
}
Expand Down
8 changes: 8 additions & 0 deletions packages/formatter/src/FormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PHPUnit\Framework\Attributes\CoversClass;

use function config;
use function pow;
use function str_replace;

use const PHP_INT_MAX;
Expand Down Expand Up @@ -274,6 +275,13 @@ public function testFilesize(): void {
self::assertEquals('10.00 GiB', $this->formatter->filesize(10 * 1024 * 1024 * 1024, 2));
self::assertEquals('0.87 EiB', $this->formatter->filesize(999_999_999_999_999_999, 2));
self::assertEquals('8.00 EiB', $this->formatter->filesize(PHP_INT_MAX, 2));
self::assertEquals('10.00 QiB', $this->formatter->filesize(10 * pow(2, 100), 2));
self::assertEquals('10.00 QiB', $this->formatter->filesize('12676506002282294014967032053760', 2));
self::assertEquals('100.00 QiB', $this->formatter->filesize('126765060022822940149670320537699', 2));
self::assertEquals(
'10,000.00 QiB',
$this->formatter->filesize(10 * 1000 * pow(2, 100), 2),
);
}

public function testDisksize(): void {
Expand Down

0 comments on commit 56b83fa

Please sign in to comment.