Skip to content

Commit

Permalink
forward valid numeric values to transform()
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Feb 9, 2019
1 parent bb54e40 commit c46cee5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
Expand Up @@ -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) {
Expand Down Expand Up @@ -58,7 +64,7 @@ public function transform($value)
if (!is_numeric($value)) {
throw new TransformationFailedException('Expected a numeric.');
}
$value = (string) ($value / $this->divisor);
$value /= $this->divisor;
}

return parent::transform($value);
Expand Down
Expand Up @@ -78,6 +78,11 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface

private $scale;

/**
* @param int $scale
* @param bool|null $grouping
* @param int|null $roundingMode
*/
public function __construct($scale = null, $grouping = false, $roundingMode = self::ROUND_HALF_UP)
{
if (null === $grouping) {
Expand Down
Expand Up @@ -17,6 +17,18 @@

class MoneyToLocalizedStringTransformerTest extends TestCase
{
private $previousLocale;

protected function setUp()
{
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
Expand Down Expand Up @@ -73,7 +85,7 @@ public function testReverseTransformEmpty()
$this->assertNull($transformer->reverseTransform(''));
}

public function testFloatToIntConversionMismatchOnReversTransform()
public function testFloatToIntConversionMismatchOnReverseTransform()
{
$transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100);
IntlTestHelper::requireFullIntl($this, false);
Expand All @@ -90,4 +102,16 @@ public function testFloatToIntConversionMismatchOnTransform()

$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));
}
}

0 comments on commit c46cee5

Please sign in to comment.