Skip to content

Commit

Permalink
don't lose int precision with not needed type casts
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Feb 4, 2019
1 parent 205b0ba commit 72136f1
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 3 deletions.
Expand Up @@ -44,4 +44,12 @@ public function reverseTransform($value)

return null !== $result ? (int) $result : null;
}

/**
* @internal
*/
protected function castParsedValue($value)
{
return $value;
}
}
Expand Up @@ -181,9 +181,7 @@ public function reverseTransform($value)
throw new TransformationFailedException('I don\'t have a clear idea what infinity looks like');
}

if (\is_int($result) && $result === (int) $float = (float) $result) {
$result = $float;
}
$result = $this->castParsedValue($result);

if (false !== $encoding = mb_detect_encoding($value, null, true)) {
$length = mb_strlen($value, $encoding);
Expand Down Expand Up @@ -228,6 +226,18 @@ protected function getNumberFormatter()
return $formatter;
}

/**
* @internal
*/
protected function castParsedValue($value)
{
if (\is_int($value) && $value === (int) $float = (float) $value) {
return $float;
}

return $value;
}

/**
* Rounds a number according to the configured scale and rounding mode.
*
Expand Down
Expand Up @@ -50,4 +50,45 @@ public function testSubmitNullUsesDefaultEmptyData($emptyData = '10', $expectedD
$this->assertSame($expectedData, $form->getNormData());
$this->assertSame($expectedData, $form->getData());
}

public function testSubmittedLargeIntegersAreNotCastToFloat()
{
if (4 === \PHP_INT_SIZE) {
$this->markTestSkipped('This test requires a 64bit PHP.');
}

$form = $this->factory->create(static::TESTED_TYPE);
$form->submit('201803221011791');

$this->assertSame(201803221011791, $form->getData());
$this->assertSame('201803221011791', $form->getViewData());
}

public function testTooSmallIntegersAreNotValid()
{
if (4 === \PHP_INT_SIZE) {
$min = '-2147483649';
} else {
$min = '-9223372036854775808';
}

$form = $this->factory->create(static::TESTED_TYPE);
$form->submit($min);

$this->assertFalse($form->isSynchronized());
}

public function testTooGreatIntegersAreNotValid()
{
if (4 === \PHP_INT_SIZE) {
$max = '2147483648';
} else {
$max = '9223372036854775808';
}

$form = $this->factory->create(static::TESTED_TYPE);
$form->submit($max);

$this->assertFalse($form->isSynchronized());
}
}

0 comments on commit 72136f1

Please sign in to comment.