diff --git a/src/JsonSchema/Constraints/FormatConstraint.php b/src/JsonSchema/Constraints/FormatConstraint.php index 12c6a2bf..1a4f8492 100644 --- a/src/JsonSchema/Constraints/FormatConstraint.php +++ b/src/JsonSchema/Constraints/FormatConstraint.php @@ -8,7 +8,9 @@ */ namespace JsonSchema\Constraints; + use JsonSchema\Rfc3339; +use InvalidArgumentException; /** * Validates against the "format" property @@ -18,6 +20,9 @@ */ class FormatConstraint extends Constraint { + protected $map = array( + 'phone' => 'JsonSchema\Constraints\Validators\PhoneValidator' + ); /** * {@inheritDoc} */ @@ -27,6 +32,15 @@ public function check($element, $schema = null, $path = null, $i = null) return; } + if(array_key_exists($schema->format, $this->map)) { + try { + (new $this->map[$schema->format])($element); + } catch(InvalidArgumentException $e) { + $this->addError($path, $e->getMessage(), 'format', array('format' => $schema->format,)); + } + return; + } + switch ($schema->format) { case 'date': if (!$date = $this->validateDateTime($element, 'Y-m-d')) { @@ -70,12 +84,6 @@ public function check($element, $schema = null, $path = null, $i = null) } break; - case 'phone': - if (!$this->validatePhone($element)) { - $this->addError($path, "Invalid phone number", 'format', array('format' => $schema->format,)); - } - break; - case 'uri': if (null === filter_var($element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE)) { $this->addError($path, "Invalid URL format", 'format', array('format' => $schema->format,)); @@ -154,11 +162,6 @@ protected function validateStyle($style) return empty($invalidEntries); } - protected function validatePhone($phone) - { - return preg_match('/^\+?(\(\d{3}\)|\d{3}) \d{3} \d{4}$/', $phone); - } - protected function validateHostname($host) { return preg_match('/^[_a-z]+\.([_a-z]+\.?)+$/i', $host); diff --git a/src/JsonSchema/Constraints/Validators/PhoneValidator.php b/src/JsonSchema/Constraints/Validators/PhoneValidator.php new file mode 100644 index 00000000..919d41be --- /dev/null +++ b/src/JsonSchema/Constraints/Validators/PhoneValidator.php @@ -0,0 +1,22 @@ +