From 702cdd7fbde99839efbfab350f677c0e24d71ad2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Robles?= Date: Mon, 25 Dec 2023 13:12:48 +0100 Subject: [PATCH] add `ByteUnitConverter::nearestUnit` method --- src/ByteUnitConverter.php | 29 +++++++++++++++++++++++++++++ tests/ByteUnitConverterTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/ByteUnitConverter.php b/src/ByteUnitConverter.php index 85aadca..b8e3db5 100644 --- a/src/ByteUnitConverter.php +++ b/src/ByteUnitConverter.php @@ -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. */ diff --git a/tests/ByteUnitConverterTest.php b/tests/ByteUnitConverterTest.php index e23bc9d..e9e0920 100644 --- a/tests/ByteUnitConverterTest.php +++ b/tests/ByteUnitConverterTest.php @@ -6,6 +6,7 @@ use OpenSoutheners\ByteUnitConverter\ByteUnit; use OpenSoutheners\ByteUnitConverter\ByteUnitConverter; +use OpenSoutheners\ByteUnitConverter\MetricSystem; use PHPUnit\Framework\TestCase; enum MyOwnByteUnit: string @@ -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) + ); + } }