bug #36905 [Validator] Catch expected ValueError (derrabus)

This PR was merged into the 3.4 branch.

Discussion
----------

[Validator] Catch expected ValueError

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | #36872
| License       | MIT
| Doc PR        | N/A

`mb_check_encoding()` raises a `ValueError` on php 8 if an invalid encoding was passed. The validator that was patched here is expected to fail gracefully in that situation. This PR restores that behavior under php 8.

Maybe we can reconsider this behavior for Symfony 5.2. It feels a bit odd to me because we swallow a potential misconfiguration of the validator.

Commits
-------

8f3f67f82a [Validator] Catch expected ValueError.
This commit is contained in:
Nicolas Grekas 2020-05-23 09:32:18 +02:00
commit 42692d625d
1 changed files with 10 additions and 2 deletions

View File

@ -39,8 +39,14 @@ class LengthValidator extends ConstraintValidator
$stringValue = (string) $value;
if (!$invalidCharset = !@mb_check_encoding($stringValue, $constraint->charset)) {
$length = mb_strlen($stringValue, $constraint->charset);
try {
$invalidCharset = !@mb_check_encoding($stringValue, $constraint->charset);
} catch (\ValueError $e) {
if (!str_starts_with($e->getMessage(), 'mb_check_encoding(): Argument #2 ($encoding) must be a valid encoding')) {
throw $e;
}
$invalidCharset = true;
}
if ($invalidCharset) {
@ -54,6 +60,8 @@ class LengthValidator extends ConstraintValidator
return;
}
$length = mb_strlen($stringValue, $constraint->charset);
if (null !== $constraint->max && $length > $constraint->max) {
$this->context->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))