Force Luhn Validator to only work with strings

The Luhn Validator fails to work with float or large integers (internally turned into float by php, depending on precision setting).
This is problematic because developers might use number or integer form fields to capture credit card data, which will lead to a validation error even though the form input itself was valid. This commit makes validator throw UnexpectedTypeException on non-string input to avoid this confusion.
This commit is contained in:
Daniel Richter 2013-10-04 01:03:44 -07:00 committed by Fabien Potencier
parent 78e9acbbc5
commit 1e410c7bcb
2 changed files with 29 additions and 0 deletions

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* Validates a PAN using the LUHN Algorithm
@ -38,6 +39,13 @@ class LuhnValidator extends ConstraintValidator
return;
}
/**
* need to work with strings only because long numbers are treated as floats and don't work with strlen
*/
if (!is_string($value)) {
throw new UnexpectedTypeException($value, 'string');
}
if (!is_numeric($value)) {
$this->context->addViolation($constraint->message);

View File

@ -103,7 +103,28 @@ class LuhnValidatorTest extends \PHPUnit_Framework_TestCase
array('1234567812345678'),
array('4222222222222222'),
array('0000000000000000'),
);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
* @dataProvider getInvalidTypes
*/
public function testInvalidTypes($number)
{
$constraint = new Luhn();
$this->validator->validate($number, $constraint);
}
public function getInvalidTypes()
{
return array(
array(0),
array(123),
array(42424242424242424242),
array(378282246310005),
array(371449635398431),
);
}
}