Skip to content

Commit

Permalink
Take into account currency when transforming form data
Browse files Browse the repository at this point in the history
  • Loading branch information
benr77 committed Apr 5, 2023
1 parent 58e3f03 commit 8625050
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
18 changes: 15 additions & 3 deletions src/Form/DataTransformer/MoneyToIntegerTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

namespace Headsnet\MoneyBundle\Form\DataTransformer;

use Money\Currency;
use Money\Money;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
Expand All @@ -19,6 +20,13 @@
*/
class MoneyToIntegerTransformer implements DataTransformerInterface
{
private Currency $currency;

public function __construct(string $currency)
{
$this->currency = new Currency($currency);
}

/**
* Transforms a Money object to a numeric string.
*
Expand All @@ -43,11 +51,15 @@ public function transform($value): string
public function reverseTransform($value): Money
{
if (null === $value) {
return Money::EUR(0);
return new Money(
0,
$this->currency
);
}

return Money::EUR(
sprintf('%.0F', $value)
return new Money(
sprintf('%.0F', $value),
$this->currency
);
}
}
4 changes: 3 additions & 1 deletion src/Form/Type/MoneyType.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ class MoneyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addModelTransformer(new MoneyToIntegerTransformer());
$builder->addModelTransformer(
new MoneyToIntegerTransformer($options['currency'])
);
}

public function configureOptions(OptionsResolver $resolver): void
Expand Down

0 comments on commit 8625050

Please sign in to comment.