Skip to content

Commit faaa4fe

Browse files
committed
bug symfony#13527 [Validator] drop grapheme_strlen in LengthValidator (nicolas-grekas)
This PR was merged into the 2.3 branch. Discussion ---------- [Validator] drop grapheme_strlen in LengthValidator | Q | A | ------------- | --- | Bug fix? | yes | New feature? | no | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | symfony#13491 | License | MIT | Doc PR | - As stated in symfony#13491, validating the length of a string with grapheme_strlen is not suited to validating input because a very long string can in fact have a length of 1 when counted with grapheme_strlen. Counting UTF-8 characters (not clusters) is not subject to this problem. The attached patch removes using grapheme_strlen but also adds more fallback when couting the length of strings, using iconv (which is more broadly avail. than mbstring) or PCRE for UTF-8 strings. Commits ------- 915fcd8 [Validator] drop grapheme_strlen in LengthValidator
2 parents 975b8a8 + 915fcd8 commit faaa4fe

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/Symfony/Component/Validator/Constraints/LengthValidator.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,20 @@ public function validate($value, Constraint $constraint)
3535

3636
$stringValue = (string) $value;
3737

38-
if (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
39-
$length = grapheme_strlen($stringValue);
38+
if ('UTF8' === $charset = strtoupper($constraint->charset)) {
39+
$charset = 'UTF-8';
40+
}
41+
42+
if (function_exists('iconv_strlen')) {
43+
$length = iconv_strlen($stringValue, $constraint->charset);
4044
} elseif (function_exists('mb_strlen')) {
4145
$length = mb_strlen($stringValue, $constraint->charset);
42-
} else {
46+
} elseif ('UTF-8' !== $charset) {
4347
$length = strlen($stringValue);
48+
} elseif (function_exists('utf8_decode')) {
49+
$length = strlen(utf8_decode($stringValue));
50+
} else {
51+
preg_replace('/./u', '', $stringValue, -1, $length);
4452
}
4553

4654
if ($constraint->min == $constraint->max && $length != $constraint->min) {

0 commit comments

Comments
 (0)