From 8625050cdf3c5c2c1eb21a61b735635465450006 Mon Sep 17 00:00:00 2001 From: Ben Roberts Date: Wed, 5 Apr 2023 15:04:07 +0200 Subject: [PATCH] Take into account currency when transforming form data --- .../MoneyToIntegerTransformer.php | 18 +++++++++++++++--- src/Form/Type/MoneyType.php | 4 +++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/Form/DataTransformer/MoneyToIntegerTransformer.php b/src/Form/DataTransformer/MoneyToIntegerTransformer.php index 8d2e202..e7ac96d 100644 --- a/src/Form/DataTransformer/MoneyToIntegerTransformer.php +++ b/src/Form/DataTransformer/MoneyToIntegerTransformer.php @@ -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; @@ -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. * @@ -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 ); } } diff --git a/src/Form/Type/MoneyType.php b/src/Form/Type/MoneyType.php index e85d455..b9f97c9 100644 --- a/src/Form/Type/MoneyType.php +++ b/src/Form/Type/MoneyType.php @@ -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