@@ -37,26 +37,35 @@ public function validate($value, Constraint $constraint)
37
37
throw new UnexpectedTypeException ($ value , 'string ' );
38
38
}
39
39
40
+ $ value = (string ) $ value ;
41
+
40
42
// Compose regex pattern
41
43
$ 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 ."$/ " ;
44
46
45
47
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 ));
49
56
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 };
54
59
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
+ }
56
64
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
+ ));
60
69
}
61
70
}
62
71
}
0 commit comments