8000 [Validator] Fixed string conversion in constraint violations by webmozart · Pull Request #10687 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Fixed string conversion in constraint violations #10687

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jul 30, 2014
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[Validator] Simplified and explained the LuhnValidator
  • Loading branch information
webmozart committed Jul 24, 2014
commit f3295522efcd5d0bd43eff48e16592051bf2c915
44 changes: 32 additions & 12 deletions src/Symfony/Component/Validator/Constraints/LuhnValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,28 +39,48 @@ public function validate($value, Constraint $constraint)
return;
}

/**
* need to work with strings only because long numbers are treated as floats and don't work with strlen
*/
if (!is_string($value)) {
// Work with strings only, because long numbers are represented as floats
// internally and don't work with strlen()
if (!is_string($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}

if (!is_numeric($value)) {
$this->context->addViolation($constraint->message);
$value = (string) $value;

if (!ctype_digit($value)) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $value,
));

return;
}

$checkSum = 0;
$length = strlen($value);
$oddLength = $length % 2;
for ($sum = 0, $i = $length - 1; $i >= 0; $i--) {
$digit = (int) $value[$i];
$sum += (($i % 2) === $oddLength) ? array_sum(str_split($digit * 2)) : $digit;

// Starting with the last digit and walking left, add every second
// digit to the check sum
// e.g. 7 9 9 2 7 3 9 8 7 1 3
// ^ ^ ^ ^ ^ ^
// = 7 + 9 + 7 + 9 + 7 + 3
for ($i = $length - 1; $i >= 0; $i -= 2) {
$checkSum += $value{$i};
}

// Starting with the second last digit and walking left, double every
// second digit and add it to the check sum
// For doubles greater than 9, sum the individual digits
// e.g. 7 9 9 2 7 3 9 8 7 1 3
// ^ ^ ^ ^ ^
// = 1+8 + 4 + 6 + 1+6 + 2
for ($i = $length - 2; $i >= 0; $i -= 2) {
$checkSum += array_sum(str_split($value{$i} * 2));
}

if ($sum === 0 || ($sum % 10) !== 0) {
$this->context->addViolation($constraint->message);
if (0 === $checkSum || 0 !== $checkSum % 10) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $value,
));
}
}
}
0