Skip to content

Use mb_strlen instead of strlen when mbstring extension is available. #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 25, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/JsonSchema/Constraints/String.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ class String extends Constraint
public function check($element, $schema = null, $path = null, $i = null)
{
// Verify maxLength
if (isset($schema->maxLength) && strlen($element) > $schema->maxLength) {
if (isset($schema->maxLength) && $this->strlen($element) > $schema->maxLength) {
$this->addError($path, "must be at most " . $schema->maxLength . " characters long");
}

//verify minLength
if (isset($schema->minLength) && strlen($element) < $schema->minLength) {
if (isset($schema->minLength) && $this->strlen($element) < $schema->minLength) {
$this->addError($path, "must be at least " . $schema->minLength . " characters long");
}

Expand All @@ -39,4 +39,13 @@ public function check($element, $schema = null, $path = null, $i = null)

$this->checkFormat($element, $schema, $path, $i);
}

private function strlen($string)
{
if (extension_loaded('mbstring')) {
return mb_strlen($string, mb_detect_encoding($string));
} else {
return strlen($string);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

/*
* This file is part of the JsonSchema package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace JsonSchema\Tests\Constraints;

class MinLengthMaxLengthMultiByteTest extends BaseTestCase
{
protected function setUp()
{
if (! extension_loaded('mbstring')) {
$this->markTestSkipped('mbstring extension is not available');
}
}

public function getInvalidTests()
{
return array(
array(
'{
"value":"☀"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","minLength":2,"maxLength":4}
}
}'
),
array(
'{
"value":"☀☁☂☃☺"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","minLength":2,"maxLength":4}
}
}'
)
);
}

public function getValidTests()
{
return array(
array(
'{
"value":"☀☁"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","minLength":2,"maxLength":4}
}
}'
),
array(
'{
"value":"☀☁☂☃"
}',
'{
"type":"object",
"properties":{
"value":{"type":"string","minLength":2,"maxLength":4}
}
}'
)
);
}
}