-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Description
Description
At the moment, a Length
Validator checks the string length using mb_strlen()
, which is fine in most cases. But in some contexts, it would be very helpful, when those Validators would be configurable in the way, how they determine the string length. The String component brought us the sweet taste of ByteString
, CodePointString
and UnicodeString
, so configuring the used class for the Validator could be nice. Have a look at this code snippet to understand what I mean:
// where '🧚♀️' is the "Woman Fairy" Emoji
dump(mb_strlen('🧚♀️')); // => 4
dump((new ByteString('🧚♀️'))->length()); // => 13
dump((new CodePointString('🧚♀️'))->length()); // => 4
dump((new UnicodeString('🧚♀️'))->length()); // => 1
Example
For example in a database context with a certain varchar length it is very important to control, how the max length of a string is determined. Or in a Twitter-like context with an arbitrarily chosen length restriction, Emojis should count as one "character" (meaning a Grapheme here) and the Length
Validator should be able to reflect that. So wouldn't it be nice, if we could do something like this:
new \Symfony\Component\Validator\Constraints\Length(
min: 1,
max: 280,
stringClass: \Symfony\Component\String\UnicodeString::class, // could be checked to be a subclass of \Symfony\Component\String\AbstractString::class
);
With that the value would be checked using a length determined by $length = (new $stringClass($value))->length();
with a default/fallback to mb_strlen()
, when the String component is not installed.
At the moment, I use custom Validators implementing that, but that is not that fun to maintain as it sounds. I could submit a PR implementing that into the string-length-checking Constraints and Validators, if that would be appreciated. I see @webmozart as the author of the Length
Constraint, what's your opinion on that?