Skip to content

Commit

Permalink
Refactor normalizeAmountToString method to handle currencies with dif…
Browse files Browse the repository at this point in the history
…ferent decimal places
  • Loading branch information
tdwesten committed Mar 13, 2024
1 parent 99790b1 commit 9133cf1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Managers/MollieManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public function createPayment(
?int $amount = null
): Payment {
$amount = $amount ?? $cart->total->value;
$currency = $cart->currency;

$meta = (array) $cart->meta;

Expand All @@ -56,7 +57,7 @@ public function createPayment(
$payment = [
'amount' => [
'currency' => $cart->currency->code,
'value' => self::normalizeAmountToString($amount),
'value' => self::normalizeAmountToString($amount, $currency->decimal_places),
],
'description' => $description,
'redirectUrl' => self::getRedirectUrl($cart),
Expand Down Expand Up @@ -183,7 +184,11 @@ public static function getCancelUrl(Cart $cart): string
*/
public static function normalizeAmountToString(int $amount, int $decimal_places = 2): string
{
return number_format($amount / 100, $decimal_places, '.', '');

// 2950000
$v = (int) str_pad('1', $decimal_places + 1, '0', STR_PAD_RIGHT);

return number_format($amount / $v, 2, '.', '');
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/Feature/CreatePaymentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,31 @@
expect($amount)->toBeInt();
expect($amount)->toBe(200000);
});

test('can normalize amount to string', function () {
$amount = MollieManager::normalizeAmountToString(2000);
expect($amount)->toBeString();
expect($amount)->toBe('20.00');

$amount = MollieManager::normalizeAmountToString(2096);
expect($amount)->toBeString();
expect($amount)->toBe('20.96');

$amount = MollieManager::normalizeAmountToString(2060);
expect($amount)->toBeString();
expect($amount)->toBe('20.60');
});

test('can normalize amount to string for a currency with 4 decimals', function () {
$amount = MollieManager::normalizeAmountToString(200000, 4);
expect($amount)->toBeString();
expect($amount)->toBe('20.00');

$amount = MollieManager::normalizeAmountToString(209600, 4);
expect($amount)->toBeString();
expect($amount)->toBe('20.96');

$amount = MollieManager::normalizeAmountToString(206000, 4);
expect($amount)->toBeString();
expect($amount)->toBe('20.60');
});

0 comments on commit 9133cf1

Please sign in to comment.