| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the JsonSchema package. |
| 5 |
* |
| 6 |
* For the full copyright and license information, please view the LICENSE |
| 7 |
* file that was distributed with this source code. |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace JsonSchema\Constraints; |
| 11 |
|
| 12 |
use JsonSchema\Entity\JsonPointer; |
| 13 |
|
| 14 |
/** |
| 15 |
* The StringConstraint Constraints, validates an string against a given schema |
| 16 |
* |
| 17 |
* @author Robert Schönthal <[email protected]> |
| 18 |
* @author Bruno Prieto Reis <[email protected]> |
| 19 |
*/ |
| 20 |
class StringConstraint extends Constraint |
| 21 |
{ |
| 22 |
/** |
| 23 |
* {@inheritdoc} |
| 24 |
*/ |
| 25 |
public function check(&$element, $schema = null, ?JsonPointer $path = null, $i = null) |
| 26 |
{ |
| 27 |
// Verify maxLength |
| 28 |
if (isset($schema->maxLength) && $this->strlen($element) > $schema->maxLength) { |
| 29 |
$this->addError($path, 'Must be at most ' . $schema->maxLength . ' characters long', 'maxLength', array( |
| 30 |
'maxLength' => $schema->maxLength, |
| 31 |
)); |
| 32 |
} |
| 33 |
|
| 34 |
//verify minLength |
| 35 |
if (isset($schema->minLength) && $this->strlen($element) < $schema->minLength) { |
| 36 |
$this->addError($path, 'Must be at least ' . $schema->minLength . ' characters long', 'minLength', array( |
| 37 |
'minLength' => $schema->minLength, |
| 38 |
)); |
| 39 |
} |
| 40 |
|
| 41 |
// Verify a regex pattern |
| 42 |
if (isset($schema->pattern) && !preg_match('#' . str_replace('#', '\\#', $schema->pattern) . '#u', $element)) { |
| 43 |
$this->addError($path, 'Does not match the regex pattern ' . $schema->pattern, 'pattern', array( |
| 44 |
'pattern' => $schema->pattern, |
| 45 |
)); |
| 46 |
} |
| 47 |
|
| 48 |
$this->checkFormat($element, $schema, $path, $i); |
| 49 |
} |
| 50 |
|
| 51 |
private function strlen($string) |
| 52 |
{ |
| 53 |
if (extension_loaded('mbstring')) { |
| 54 |
return mb_strlen($string, mb_detect_encoding($string)); |
| 55 |
} |
| 56 |
|
| 57 |
// mbstring is present on all test platforms, so strlen() can be ignored for coverage |
| 58 |
return strlen($string); // @codeCoverageIgnore |
| 59 |
} |
| 60 |
} |