diff --git a/src/JsonSchema/Constraints/String.php b/src/JsonSchema/Constraints/String.php index 7bc3eb83..246c06b4 100644 --- a/src/JsonSchema/Constraints/String.php +++ b/src/JsonSchema/Constraints/String.php @@ -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"); } @@ -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); + } + } } diff --git a/tests/JsonSchema/Tests/Constraints/MinLengthMaxLengthMultiByteTest.php b/tests/JsonSchema/Tests/Constraints/MinLengthMaxLengthMultiByteTest.php new file mode 100644 index 00000000..df00ce42 --- /dev/null +++ b/tests/JsonSchema/Tests/Constraints/MinLengthMaxLengthMultiByteTest.php @@ -0,0 +1,76 @@ +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} + } + }' + ) + ); + } +}