Skip to content

Commit

Permalink
refactor: differentiate between kilo/kibibytes and mega/mebibytes
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasMeschke committed Nov 13, 2024
1 parent fff0c87 commit de53b38
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
8 changes: 6 additions & 2 deletions system/Files/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,18 @@ public function getSize()

/**
* Retrieve the file size by unit.
* Supports the metric units "kb" and "mb"
* and the IEC units "kib" and "mib".
*
* @return false|int|string
*/
public function getSizeByUnit(string $unit = 'b')
{
return match (strtolower($unit)) {
'kb' => number_format($this->getSize() / 1024, 3),
'mb' => number_format(($this->getSize() / 1024) / 1024, 3),
'kb' => number_format($this->getSize() / 1000, 3),
'kib' => number_format($this->getSize() / 1024, 3),
'mb' => number_format(($this->getSize() / 1000) / 1000, 3),
'mib' => number_format(($this->getSize() / 1024) / 1024, 3),
default => $this->getSize(),
};
}
Expand Down
18 changes: 16 additions & 2 deletions tests/system/Files/FileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,31 @@ public function testCanAccessSplFileInfoMethods(): void
$this->assertSame('file', $file->getType());
}

public function testGetSizeReturnsKB(): void
public function testGetSizeReturnsKiB(): void
{
$file = new File(SYSTEMPATH . 'Common.php');
$size = number_format(filesize(SYSTEMPATH . 'Common.php') / 1024, 3);
$this->assertSame($size, $file->getSizeByUnit('kib'));
}

public function testGetSizeReturnsKB(): void
{
$file = new File(SYSTEMPATH . 'Common.php');
$size = number_format(filesize(SYSTEMPATH . 'Common.php') / 1000, 3);
$this->assertSame($size, $file->getSizeByUnit('kb'));
}

public function testGetSizeReturnsMB(): void
public function testGetSizeReturnsMiB(): void
{
$file = new File(SYSTEMPATH . 'Common.php');
$size = number_format(filesize(SYSTEMPATH . 'Common.php') / 1024 / 1024, 3);
$this->assertSame($size, $file->getSizeByUnit('mib'));
}

public function testGetSizeReturnsMB(): void
{
$file = new File(SYSTEMPATH . 'Common.php');
$size = number_format(filesize(SYSTEMPATH . 'Common.php') / 1000 / 1000, 3);
$this->assertSame($size, $file->getSizeByUnit('mb'));
}

Expand Down

0 comments on commit de53b38

Please sign in to comment.