Skip to content

Commit

Permalink
add ByteUnitConverter::nearestUnit method
Browse files Browse the repository at this point in the history
  • Loading branch information
d8vjork committed Dec 25, 2023
1 parent a52514b commit 702cdd7
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/ByteUnitConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,35 @@ public function useUnitLabel(bool $value = true): self
return $this;
}

/**
* Assign nearest bytes unit by metric system from current bytes value.
*/
public function nearestUnit(?MetricSystem $metric = MetricSystem::Decimal, ByteUnit $stoppingAt = null): self
{
$nearestUnit = null;
$byteUnits = ByteUnit::cases();
$i = 0;

while (! $nearestUnit && $i < count($byteUnits)) {
$unit = $byteUnits[$i];
$unitMetricSystem = $unit->getMetric();

$i++;

if (! $unitMetricSystem || $unitMetricSystem !== $metric) {
continue;
}

if ($unit === $stoppingAt || ($this->bytes - $unit->value) >= 0) {
$nearestUnit = $unit;
}
}

$this->unit = $nearestUnit ?? ByteUnit::B;

return $this;
}

/**
* Get conversion result numeric value.
*/
Expand Down
29 changes: 29 additions & 0 deletions tests/ByteUnitConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use OpenSoutheners\ByteUnitConverter\ByteUnit;
use OpenSoutheners\ByteUnitConverter\ByteUnitConverter;
use OpenSoutheners\ByteUnitConverter\MetricSystem;
use PHPUnit\Framework\TestCase;

enum MyOwnByteUnit: string
Expand Down Expand Up @@ -162,4 +163,32 @@ public function testConversionToBytesDoesNotGiveDecimals()
(string) ByteUnitConverter::new('1000')
);
}

public function testConversionToNearestUnitPrintsConvertedByteUnitAndMetricSystem()
{
$this->assertEquals(
'1.00 KB',
(string) ByteUnitConverter::new('1000')->nearestUnit()
);

$this->assertEquals(
'1.02 KB',
(string) ByteUnitConverter::new('1024')->nearestUnit()
);

$this->assertEquals(
'1.00 KiB',
(string) ByteUnitConverter::new('1024')->nearestUnit(MetricSystem::Binary)
);

$this->assertEquals(
'1000 B',
(string) ByteUnitConverter::new('1000')->nearestUnit(MetricSystem::Binary)
);

$this->assertEquals(
'0.97 KiB',
(string) ByteUnitConverter::new('1000')->nearestUnit(MetricSystem::Binary, ByteUnit::KiB)
);
}
}

0 comments on commit 702cdd7

Please sign in to comment.