Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit bff09f2

Browse filesBrowse files
committed
[Validator] Simplified IssnValidator
1 parent 224e70f commit bff09f2
Copy full SHA for bff09f2

File tree

Expand file treeCollapse file tree

1 file changed

+22
-13
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+22
-13
lines changed

‎src/Symfony/Component/Validator/Constraints/IssnValidator.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Validator/Constraints/IssnValidator.php
+22-13Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,35 @@ public function validate($value, Constraint $constraint)
3737
throw new UnexpectedTypeException($value, 'string');
3838
}
3939

40+
$value = (string) $value;
41+
4042
// Compose regex pattern
4143
$digitsPattern = $constraint->requireHyphen ? '\d{4}-\d{3}' : '\d{4}-?\d{3}';
42-
$checksumPattern = $constraint->caseSensitive ? '[\d|X]' : '[\d|X|x]';
43-
$pattern = "/^".$digitsPattern.$checksumPattern."$/";
44+
$checkSumPattern = $constraint->caseSensitive ? '[\d|X]' : '[\d|X|x]';
45+
$pattern = "/^".$digitsPattern.$checkSumPattern."$/";
4446

4547
if (!preg_match($pattern, $value)) {
46-
$this->context->addViolation($constraint->message);
47-
} else {
48-
$digits = str_split(strtoupper(str_replace('-', '', $value)));
48+
$this->context->addViolation($constraint->message, array(
49+
'{{ value }}' => $value,
50+
));
51+
52+
return;
53+
}
54+
55+
$canonical = strtoupper(str_replace('-', '', $value));
4956

50-
$sum = 0;
51-
for ($i = 8; $i > 1; $i--) {
52-
$sum += $i * (int) array_shift($digits);
53-
}
57+
// Calculate a checksum. "X" equals 10.
58+
$checkSum = 'X' === $canonical{7} ? 10 : $canonical{7};
5459

55-
$checksum = 'X' == reset($digits) ? 10 : (int) reset($digits);
60+
for ($i = 0; $i < 7; ++$i) {
61+
// Multiply the first digit by 8, the second by 7, etc.
62+
$checkSum += (8-$i) * $canonical{$i};
63+
}
5664

57-
if (0 != ($sum + $checksum) % 11) {
58-
$this->context->addViolation($constraint->message);
59-
}
65+
if (0 !== $checkSum % 11) {
66+
$this->context->addViolation($constraint->message, array(
67+
'{{ value }}' => $value,
68+
));
6069
}
6170
}
6271
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.