Skip to content

Commit

Permalink
feature #6055 feat: allow custom money divisor (KDederichs)
Browse files Browse the repository at this point in the history
This PR was merged into the 4.x branch.

Discussion
----------

feat: allow custom money divisor

Fixes #6054 by only setting the divisor when it's not already set, and in case of a custom one (not 1 or 100) use it to divide.

Commits
-------

f065345 feat: allow custom money divisor
  • Loading branch information
javiereguiluz committed Dec 7, 2023
2 parents 7182c05 + f065345 commit a531172
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/Field/Configurator/MoneyConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,20 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$field->setFormTypeOption('scale', $numDecimals);

$isStoredAsCents = true === $field->getCustomOption(MoneyField::OPTION_STORED_AS_CENTS);
$field->setFormTypeOption('divisor', $isStoredAsCents ? 100 : 1);
$field->setFormTypeOptionIfNotSet('divisor', $isStoredAsCents ? 100 : 1);

$divisor = $field->getFormTypeOption('divisor');
$isCustomDivisor = 1 !== $divisor && 100 !== $divisor;

if (null === $field->getValue()) {
return;
}

$amount = $isStoredAsCents ? $field->getValue() / 100 : $field->getValue();
if ($isCustomDivisor) {
$amount = $field->getValue() / $divisor;
} else {
$amount = $isStoredAsCents ? $field->getValue() / 100 : $field->getValue();
}

$formattedValue = $this->intlFormatter->formatCurrency($amount, $currencyCode, ['fraction_digit' => $numDecimals]);
$field->setFormattedValue($formattedValue);
Expand Down
15 changes: 14 additions & 1 deletion tests/Field/MoneyFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,29 @@ public function testFieldDecimals()
self::assertSame(3, $fieldDto->getFormTypeOption('scale'));
}

public function testFieldCents()
public function testFieldsDefaultsToCents()
{
$field = MoneyField::new('foo')->setValue(100)->setCurrency('EUR');
$fieldDto = $this->configure($field);
self::assertSame('1€', $fieldDto->getFormattedValue());
self::assertSame(100, $fieldDto->getFormTypeOption('divisor'));
}

public function testFieldCents()
{
$field = MoneyField::new('foo')->setValue(100)->setCurrency('EUR');
$field->setStoredAsCents(false);
$fieldDto = $this->configure($field);
self::assertSame('100€', $fieldDto->getFormattedValue());
self::assertSame(1, $fieldDto->getFormTypeOption('divisor'));
}

public function testFieldWithCustomDivisor()
{
$field = MoneyField::new('foo')->setValue(725)->setCurrency('EUR');
$field->setFormTypeOption('divisor', 10000);
$fieldDto = $this->configure($field);
self::assertSame('0.0725€', $fieldDto->getFormattedValue());
self::assertSame(10000, $fieldDto->getFormTypeOption('divisor'));
}
}

0 comments on commit a531172

Please sign in to comment.