From 52219a570d2b2b1c6ca1fb7add06c299094c5fd7 Mon Sep 17 00:00:00 2001 From: Adrien Leloup Date: Fri, 14 Jan 2022 15:49:00 +0100 Subject: [PATCH] Added toMinor method & tests --- src/Price.php | 27 +++++++++++++++++++++++---- tests/Unit/HasValueAccessorsTest.php | 27 +++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/Price.php b/src/Price.php index 36e029e..f1f9f72 100644 --- a/src/Price.php +++ b/src/Price.php @@ -187,6 +187,25 @@ public function inclusive($perUnit = false) return $result['amount']; } + /** + * Shorthand to easily get the underlying minor amount (as an integer) + * + * @param null|string $version + * @return int + */ + public function toMinor($version = null) + { + if ($version === 'inclusive') { + return $this->inclusive()->getMinorAmount()->toInt(); + } + + if ($version === 'exclusive') { + return $this->exclusive()->getMinorAmount()->toInt(); + } + + return $this->base()->getMinorAmount()->toInt(); + } + /** * Split given amount into ~equal parts and return the smallest * @@ -202,7 +221,7 @@ public function perUnit(Money $amount) $parts = floor($this->units); $remainder = $amount->multipliedBy($this->units - $parts, RoundingMode::FLOOR); - + $allocated = $amount->minus($remainder); return Money::min(...$allocated->split($parts)); @@ -253,7 +272,7 @@ public function build() } /** - * Convert this price object into a readable + * Convert this price object into a readable * total & inclusive money string * * @return string @@ -303,8 +322,8 @@ public static function json($value) } $base = Money::ofMinor($value['base'], $value['currency']); - + return (new static($base, $value['units'])) ->setVat($value['vat']); } -} \ No newline at end of file +} diff --git a/tests/Unit/HasValueAccessorsTest.php b/tests/Unit/HasValueAccessorsTest.php index c765f2f..28011b8 100644 --- a/tests/Unit/HasValueAccessorsTest.php +++ b/tests/Unit/HasValueAccessorsTest.php @@ -3,7 +3,6 @@ namespace Tests\Unit; use Brick\Money\Context; -use Brick\Money\Money; use Brick\Money\Currency; use Whitecube\Price\Price; @@ -28,4 +27,28 @@ $context = $price->context(); expect($context)->toBeInstanceOf(Context::class); -}); \ No newline at end of file +}); + +it('can access the base minor value', function() { + $price = Price::EUR(100); + + $minor = $price->toMinor(); + + expect($minor)->toBe(100); +}); + +it('can access the vat-inclusive minor value', function() { + $price = Price::EUR(100)->setVat(21); + + $minor = $price->toMinor('inclusive'); + + expect($minor)->toBe(121); +}); + +it('can access the vat-exclusive minor value', function() { + $price = Price::EUR(100)->setVat(21); + + $minor = $price->toMinor('exclusive'); + + expect($minor)->toBe(100); +});