Skip to content

Commit

Permalink
Merge pull request #303 from gsteel/v3/string-length-malformed-multibyte
Browse files Browse the repository at this point in the history
Change Malformed Multi-Byte input handling in `StringLength`
  • Loading branch information
gsteel committed Jul 2, 2024
2 parents a46f708 + b2c072f commit d4c48d5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
13 changes: 6 additions & 7 deletions src/StringLength.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use Laminas\Stdlib\StringUtils;
use Laminas\Validator\Exception\InvalidArgumentException;
use Laminas\Validator\Exception\RuntimeException;
use Throwable;

use function is_string;
Expand Down Expand Up @@ -82,20 +81,20 @@ public function isValid(mixed $value): bool
return false;
}

$this->setValue($value);

$wrapper = StringUtils::getWrapper($this->encoding);
$exception = null;
$wrapper = StringUtils::getWrapper($this->encoding);
try {
$length = $wrapper->strlen($value);
} catch (Throwable $exception) {
} catch (Throwable) {
$length = false;
}

if ($length === false) {
throw new RuntimeException('Failed to detect string length', 0, $exception);
$this->error(self::INVALID);

return false;
}

$this->setValue($value);
$this->length = $length;

if ($this->length < $this->min) {
Expand Down
17 changes: 7 additions & 10 deletions test/StringLengthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace LaminasTest\Validator;

use Laminas\Validator\Exception\InvalidArgumentException;
use Laminas\Validator\Exception\RuntimeException;
use Laminas\Validator\StringLength;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -82,7 +81,7 @@ public function testInvalidMaxOptionCausesException(): void
new StringLength(['min' => 10, 'max' => 5]);
}

public function testAnExceptionIsThrownWhenStringLengthCannotBeDetected(): void
public function testMalformedMultiByteDataWillCauseValidationFailure(): void
{
/**
* Malformed UTF-8 will likely trigger errors/warnings in `ext-intl` or `ext-mbstring`
Expand All @@ -94,13 +93,11 @@ public function testAnExceptionIsThrownWhenStringLengthCannotBeDetected(): void
// phpcs:enable

$malformed = chr(0xED) . chr(0xA0) . chr(0x80);
try {
(new StringLength())->isValid($malformed);
self::fail('No exception was thrown');
} catch (RuntimeException $error) {
self::assertSame('Failed to detect string length', $error->getMessage());
} finally {
restore_error_handler();
}

$validator = new StringLength();
self::assertFalse($validator->isValid($malformed));
self::assertArrayHasKey(StringLength::INVALID, $validator->getMessages());

restore_error_handler();
}
}

0 comments on commit d4c48d5

Please sign in to comment.