forward valid numeric values to transform()

This commit is contained in:
Christian Flothmann 2019-02-09 11:37:37 +01:00
parent bb54e40ca7
commit 3be0d35b17
3 changed files with 37 additions and 2 deletions

View File

@ -23,6 +23,12 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransform
{
private $divisor;
/**
* @param int|null $scale
* @param bool|null $grouping
* @param int|null $roundingMode
* @param int|null $divisor
*/
public function __construct($scale = 2, $grouping = true, $roundingMode = self::ROUND_HALF_UP, $divisor = 1)
{
if (null === $grouping) {
@ -58,7 +64,7 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransform
if (!is_numeric($value)) {
throw new TransformationFailedException('Expected a numeric.');
}
$value = (string) ($value / $this->divisor);
$value /= $this->divisor;
}
return parent::transform($value);

View File

@ -78,6 +78,11 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface
private $scale;
/**
* @param int|null $scale
* @param bool|null $grouping
* @param int|null $roundingMode
*/
public function __construct($scale = null, $grouping = false, $roundingMode = self::ROUND_HALF_UP)
{
if (null === $grouping) {

View File

@ -17,6 +17,18 @@ use Symfony\Component\Intl\Util\IntlTestHelper;
class MoneyToLocalizedStringTransformerTest extends TestCase
{
private $previousLocale;
protected function setUp()
{
$this->previousLocale = setlocale(LC_ALL, '0');
}
protected function tearDown()
{
setlocale(LC_ALL, $this->previousLocale);
}
public function testTransform()
{
// Since we test against "de_AT", we need the full implementation
@ -73,7 +85,7 @@ class MoneyToLocalizedStringTransformerTest extends TestCase
$this->assertNull($transformer->reverseTransform(''));
}
public function testFloatToIntConversionMismatchOnReversTransform()
public function testFloatToIntConversionMismatchOnReverseTransform()
{
$transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100);
IntlTestHelper::requireFullIntl($this, false);
@ -90,4 +102,16 @@ class MoneyToLocalizedStringTransformerTest extends TestCase
$this->assertSame('10,20', $transformer->transform(1020));
}
public function testValidNumericValuesWithNonDotDecimalPointCharacter()
{
// calling setlocale() here is important as it changes the representation of floats when being cast to strings
setlocale(LC_ALL, 'de_AT.UTF-8');
$transformer = new MoneyToLocalizedStringTransformer(4, null, null, 100);
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$this->assertSame('0,0035', $transformer->transform(12 / 34));
}
}