diff --git a/.gitignore b/.gitignore index 8972b3c2..e5ad919d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ coverage .buildpath .project .settings +.php_cs +.php_cs.cache composer.lock docs-api phpunit.xml diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 00000000..9b7f040e --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,31 @@ +in(__DIR__); + +/* Based on ^2.1 of php-cs-fixer */ +$config + ->setRules(array( + // default + '@PSR2' => true, + '@Symfony' => true, + // additionally + 'array_syntax' => array('syntax' => 'long'), + 'binary_operator_spaces' => false, + 'concat_space' => array('spacing' => 'one'), + 'no_unused_imports' => false, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'ordered_imports' => true, + 'phpdoc_no_package' => false, + 'phpdoc_order' => true, + 'phpdoc_summary' => false, + 'pre_increment' => false, + 'trailing_comma_in_multiline_array' => false, + 'simplified_null_return' => false, + )) + ->setFinder($finder) +; + +return $config; diff --git a/.travis.yml b/.travis.yml index 82f8e589..f4a65591 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ language: php cache: directories: - $HOME/.composer/cache + - $HOME/.phpcsfixer matrix: fast_finish: true @@ -13,7 +14,7 @@ matrix: - php: 5.5 - php: 5.6 - php: 7.0 - env: WITH_COVERAGE=true + env: WITH_COVERAGE=true WITH_PHPCSFIXER=true - php: 7.1 - php: 'nightly' - php: hhvm @@ -29,3 +30,4 @@ install: script: - if [[ "$WITH_COVERAGE" == "true" ]]; then ./vendor/bin/phpunit --coverage-text; else composer test; fi + - if [[ "$WITH_PHPCSFIXER" == "true" ]]; then composer require friendsofphp/php-cs-fixer:^2.1 && mkdir -p $HOME/.phpcsfixer && vendor/bin/php-cs-fixer fix --cache-file "$HOME/.phpcsfixer/.php_cs.cache" --dry-run --diff --verbose; fi diff --git a/composer.json b/composer.json index b0ad6b5f..c6257ad5 100644 --- a/composer.json +++ b/composer.json @@ -52,12 +52,12 @@ "bin": ["bin/validate-json"], "extra": { "branch-alias": { - "dev-master": "4.0.x-dev" + "dev-master": "5.0.x-dev" } }, "scripts": { "test" : "vendor/bin/phpunit", "testOnly" : "vendor/bin/phpunit --colors --filter", - "coverage" : "vendor/bin/phpunit --coverage-text" + "coverage" : "vendor/bin/phpunit --coverage-text" } } diff --git a/demo/demo.php b/demo/demo.php index e921df6f..98b518a7 100644 --- a/demo/demo.php +++ b/demo/demo.php @@ -1,11 +1,12 @@ check($data, (object)['$ref' => 'file://' . realpath('schema.json')]); +$validator = new JsonSchema\Validator(); +$validator->check($data, (object) array('$ref' => 'file://' . realpath('schema.json'))); if ($validator->isValid()) { echo "The supplied JSON validates against the schema.\n"; diff --git a/src/JsonSchema/Constraints/BaseConstraint.php b/src/JsonSchema/Constraints/BaseConstraint.php index 6c4cc42f..ef1bdc54 100644 --- a/src/JsonSchema/Constraints/BaseConstraint.php +++ b/src/JsonSchema/Constraints/BaseConstraint.php @@ -33,12 +33,9 @@ class BaseConstraint */ public function __construct(Factory $factory = null) { - $this->factory = $factory ? : new Factory(); + $this->factory = $factory ?: new Factory(); } - /** - * {@inheritDoc} - */ public function addError(JsonPointer $path = null, $message, $constraint = '', array $more = null) { $error = array( @@ -49,20 +46,16 @@ public function addError(JsonPointer $path = null, $message, $constraint = '', a ); if ($this->factory->getConfig(Constraint::CHECK_MODE_EXCEPTIONS)) { - throw new ValidationException(sprintf("Error validating %s: %s", $error['pointer'], $error['message'])); + throw new ValidationException(sprintf('Error validating %s: %s', $error['pointer'], $error['message'])); } - if (is_array($more) && count($more) > 0) - { + if (is_array($more) && count($more) > 0) { $error += $more; } $this->errors[] = $error; } - /** - * {@inheritDoc} - */ public function addErrors(array $errors) { if ($errors) { @@ -70,17 +63,11 @@ public function addErrors(array $errors) } } - /** - * {@inheritDoc} - */ public function getErrors() { return $this->errors; } - /** - * {@inheritDoc} - */ public function isValid() { return !$this->getErrors(); diff --git a/src/JsonSchema/Constraints/CollectionConstraint.php b/src/JsonSchema/Constraints/CollectionConstraint.php index e2a704e9..3c594b3c 100644 --- a/src/JsonSchema/Constraints/CollectionConstraint.php +++ b/src/JsonSchema/Constraints/CollectionConstraint.php @@ -19,30 +19,31 @@ */ class CollectionConstraint extends Constraint { - /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$value, $schema = null, JsonPointer $path = null, $i = null) { // Verify minItems if (isset($schema->minItems) && count($value) < $schema->minItems) { - $this->addError($path, "There must be a minimum of " . $schema->minItems . " items in the array", 'minItems', array('minItems' => $schema->minItems,)); + $this->addError($path, 'There must be a minimum of ' . $schema->minItems . ' items in the array', 'minItems', array('minItems' => $schema->minItems)); } // Verify maxItems if (isset($schema->maxItems) && count($value) > $schema->maxItems) { - $this->addError($path, "There must be a maximum of " . $schema->maxItems . " items in the array", 'maxItems', array('maxItems' => $schema->maxItems,)); + $this->addError($path, 'There must be a maximum of ' . $schema->maxItems . ' items in the array', 'maxItems', array('maxItems' => $schema->maxItems)); } // Verify uniqueItems if (isset($schema->uniqueItems) && $schema->uniqueItems) { $unique = $value; if (is_array($value) && count($value)) { - $unique = array_map(function($e) { return var_export($e, true); }, $value); + $unique = array_map(function ($e) { + return var_export($e, true); + }, $value); } if (count(array_unique($unique)) != count($value)) { - $this->addError($path, "There are no duplicates allowed in the array", 'uniqueItems'); + $this->addError($path, 'There are no duplicates allowed in the array', 'uniqueItems'); } } @@ -123,7 +124,7 @@ protected function validateItems(&$value, $schema = null, JsonPointer $path = nu $this->checkUndefined($v, $schema->additionalItems, $path, $k); } else { $this->addError( - $path, 'The item ' . $i . '[' . $k . '] is not defined and the definition does not allow additional items', 'additionalItems', array('additionalItems' => $schema->additionalItems,)); + $path, 'The item ' . $i . '[' . $k . '] is not defined and the definition does not allow additional items', 'additionalItems', array('additionalItems' => $schema->additionalItems)); } } else { // Should be valid against an empty schema diff --git a/src/JsonSchema/Constraints/Constraint.php b/src/JsonSchema/Constraints/Constraint.php index cc12a22c..7fa0a99a 100644 --- a/src/JsonSchema/Constraints/Constraint.php +++ b/src/JsonSchema/Constraints/Constraint.php @@ -9,10 +9,10 @@ namespace JsonSchema\Constraints; +use JsonSchema\Entity\JsonPointer; use JsonSchema\SchemaStorage; use JsonSchema\Uri\UriRetriever; use JsonSchema\UriRetrieverInterface; -use JsonSchema\Entity\JsonPointer; /** * The Base Constraints, all Validators should extend this class @@ -48,6 +48,7 @@ protected function incrementPath(JsonPointer $path = null, $i) array_filter(array($i), 'strlen') ) ); + return $path; } @@ -193,16 +194,18 @@ protected function getTypeCheck() /** * @param JsonPointer $pointer + * * @return string property path */ protected function convertJsonPointerIntoPropertyPath(JsonPointer $pointer) { $result = array_map( - function($path) { + function ($path) { return sprintf(is_numeric($path) ? '[%d]' : '.%s', $path); }, $pointer->getPropertyPaths() ); + return trim(implode('', $result), '.'); } } diff --git a/src/JsonSchema/Constraints/ConstraintInterface.php b/src/JsonSchema/Constraints/ConstraintInterface.php index 0c2922a3..442268e6 100644 --- a/src/JsonSchema/Constraints/ConstraintInterface.php +++ b/src/JsonSchema/Constraints/ConstraintInterface.php @@ -38,14 +38,14 @@ public function addErrors(array $errors); * @param JsonPointer|null $path * @param string $message * @param string $constraint the constraint/rule that is broken, e.g.: 'minLength' - * @param array $more more array elements to add to the error + * @param array $more more array elements to add to the error */ public function addError(JsonPointer $path = null, $message, $constraint='', array $more = null); /** * checks if the validator has not raised errors * - * @return boolean + * @return bool */ public function isValid(); @@ -53,10 +53,12 @@ public function isValid(); * invokes the validation of an element * * @abstract + * * @param mixed $value * @param mixed $schema * @param JsonPointer|null $path * @param mixed $i + * * @throws \JsonSchema\Exception\ExceptionInterface */ public function check(&$value, $schema = null, JsonPointer $path = null, $i = null); diff --git a/src/JsonSchema/Constraints/EnumConstraint.php b/src/JsonSchema/Constraints/EnumConstraint.php index 18c3d707..0fd2b6a0 100644 --- a/src/JsonSchema/Constraints/EnumConstraint.php +++ b/src/JsonSchema/Constraints/EnumConstraint.php @@ -8,6 +8,7 @@ */ namespace JsonSchema\Constraints; + use JsonSchema\Entity\JsonPointer; /** @@ -19,7 +20,7 @@ class EnumConstraint extends Constraint { /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$element, $schema = null, JsonPointer $path = null, $i = null) { @@ -31,14 +32,14 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i = foreach ($schema->enum as $enum) { $enumType = gettype($enum); - if ($this->factory->getConfig(self::CHECK_MODE_TYPE_CAST) && $type == "array" && $enumType == "object") { - if ((object)$element == $enum) { + if ($this->factory->getConfig(self::CHECK_MODE_TYPE_CAST) && $type == 'array' && $enumType == 'object') { + if ((object) $element == $enum) { return; } } if ($type === gettype($enum)) { - if ($type == "object") { + if ($type == 'object') { if ($element == $enum) { return; } @@ -48,6 +49,6 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i = } } - $this->addError($path, "Does not have a value in the enumeration " . json_encode($schema->enum), 'enum', array('enum' => $schema->enum,)); + $this->addError($path, 'Does not have a value in the enumeration ' . json_encode($schema->enum), 'enum', array('enum' => $schema->enum)); } } diff --git a/src/JsonSchema/Constraints/Factory.php b/src/JsonSchema/Constraints/Factory.php index 71fea365..f6b97457 100644 --- a/src/JsonSchema/Constraints/Factory.php +++ b/src/JsonSchema/Constraints/Factory.php @@ -27,7 +27,7 @@ class Factory protected $schemaStorage; /** - * @var UriRetriever $uriRetriever + * @var UriRetriever */ protected $uriRetriever; @@ -42,7 +42,7 @@ class Factory private $typeCheck = array(); /** - * @var array $constraintMap + * @var array */ protected $constraintMap = array( 'array' => 'JsonSchema\Constraints\CollectionConstraint', @@ -64,9 +64,9 @@ class Factory private $instanceCache = array(); /** - * @param SchemaStorage $schemaStorage + * @param SchemaStorage $schemaStorage * @param UriRetrieverInterface $uriRetriever - * @param int $checkMode + * @param int $checkMode */ public function __construct( SchemaStorageInterface $schemaStorage = null, @@ -76,7 +76,7 @@ public function __construct( // set provided config options $this->setConfig($checkMode); - $this->uriRetriever = $uriRetriever ?: new UriRetriever; + $this->uriRetriever = $uriRetriever ?: new UriRetriever(); $this->schemaStorage = $schemaStorage ?: new SchemaStorage($this->uriRetriever); } @@ -122,7 +122,8 @@ public function getConfig($options = null) if ($options === null) { return $this->checkMode; } - return ($this->checkMode & $options); + + return $this->checkMode & $options; } /** @@ -142,8 +143,8 @@ public function getTypeCheck() { if (!isset($this->typeCheck[$this->checkMode])) { $this->typeCheck[$this->checkMode] = ($this->checkMode & Constraint::CHECK_MODE_TYPE_CAST) - ? new TypeCheck\LooseTypeCheck - : new TypeCheck\StrictTypeCheck; + ? new TypeCheck\LooseTypeCheck() + : new TypeCheck\StrictTypeCheck(); } return $this->typeCheck[$this->checkMode]; @@ -152,6 +153,7 @@ public function getTypeCheck() /** * @param string $name * @param string $class + * * @return Factory */ public function setConstraintClass($name, $class) @@ -165,6 +167,7 @@ public function setConstraintClass($name, $class) throw new InvalidArgumentException('Invalid class ' . $name); } $this->constraintMap[$name] = $class; + return $this; } @@ -172,8 +175,10 @@ public function setConstraintClass($name, $class) * Create a constraint instance for the given constraint name. * * @param string $constraintName + * + * @throws InvalidArgumentException if is not possible create the constraint instance + * * @return ConstraintInterface|ObjectConstraint - * @throws InvalidArgumentException if is not possible create the constraint instance. */ public function createInstanceFor($constraintName) { diff --git a/src/JsonSchema/Constraints/FormatConstraint.php b/src/JsonSchema/Constraints/FormatConstraint.php index 8dc9b77c..5ea9f95b 100644 --- a/src/JsonSchema/Constraints/FormatConstraint.php +++ b/src/JsonSchema/Constraints/FormatConstraint.php @@ -9,19 +9,20 @@ namespace JsonSchema\Constraints; -use JsonSchema\Rfc3339; use JsonSchema\Entity\JsonPointer; +use JsonSchema\Rfc3339; /** * Validates against the "format" property * * @author Justin Rainbow - * @link http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.23 + * + * @see http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.23 */ class FormatConstraint extends Constraint { /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$element, $schema = null, JsonPointer $path = null, $i = null) { @@ -32,81 +33,81 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i = switch ($schema->format) { case 'date': if (!$date = $this->validateDateTime($element, 'Y-m-d')) { - $this->addError($path, sprintf('Invalid date %s, expected format YYYY-MM-DD', json_encode($element)), 'format', array('format' => $schema->format,)); + $this->addError($path, sprintf('Invalid date %s, expected format YYYY-MM-DD', json_encode($element)), 'format', array('format' => $schema->format)); } break; case 'time': if (!$this->validateDateTime($element, 'H:i:s')) { - $this->addError($path, sprintf('Invalid time %s, expected format hh:mm:ss', json_encode($element)), 'format', array('format' => $schema->format,)); + $this->addError($path, sprintf('Invalid time %s, expected format hh:mm:ss', json_encode($element)), 'format', array('format' => $schema->format)); } break; case 'date-time': if (null === Rfc3339::createFromString($element)) { - $this->addError($path, sprintf('Invalid date-time %s, expected format YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss+hh:mm', json_encode($element)), 'format', array('format' => $schema->format,)); + $this->addError($path, sprintf('Invalid date-time %s, expected format YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss+hh:mm', json_encode($element)), 'format', array('format' => $schema->format)); } break; case 'utc-millisec': if (!$this->validateDateTime($element, 'U')) { - $this->addError($path, sprintf('Invalid time %s, expected integer of milliseconds since Epoch', json_encode($element)), 'format', array('format' => $schema->format,)); + $this->addError($path, sprintf('Invalid time %s, expected integer of milliseconds since Epoch', json_encode($element)), 'format', array('format' => $schema->format)); } break; case 'regex': if (!$this->validateRegex($element)) { - $this->addError($path, 'Invalid regex format ' . $element, 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid regex format ' . $element, 'format', array('format' => $schema->format)); } break; case 'color': if (!$this->validateColor($element)) { - $this->addError($path, "Invalid color", 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid color', 'format', array('format' => $schema->format)); } break; case 'style': if (!$this->validateStyle($element)) { - $this->addError($path, "Invalid style", 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid style', 'format', array('format' => $schema->format)); } break; case 'phone': if (!$this->validatePhone($element)) { - $this->addError($path, "Invalid phone number", 'format', array('format' => $schema->format,)); + $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,)); + $this->addError($path, 'Invalid URL format', 'format', array('format' => $schema->format)); } break; case 'email': if (null === filter_var($element, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE)) { - $this->addError($path, "Invalid email", 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid email', 'format', array('format' => $schema->format)); } break; case 'ip-address': case 'ipv4': if (null === filter_var($element, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV4)) { - $this->addError($path, "Invalid IP address", 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid IP address', 'format', array('format' => $schema->format)); } break; case 'ipv6': if (null === filter_var($element, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV6)) { - $this->addError($path, "Invalid IP address", 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid IP address', 'format', array('format' => $schema->format)); } break; case 'host-name': case 'hostname': if (!$this->validateHostname($element)) { - $this->addError($path, "Invalid hostname", 'format', array('format' => $schema->format,)); + $this->addError($path, 'Invalid hostname', 'format', array('format' => $schema->format)); } break; @@ -176,6 +177,7 @@ protected function validatePhone($phone) protected function validateHostname($host) { $hostnameRegex = '/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/i'; + return preg_match($hostnameRegex, $host); } } diff --git a/src/JsonSchema/Constraints/NumberConstraint.php b/src/JsonSchema/Constraints/NumberConstraint.php index a4dd0639..5a809774 100644 --- a/src/JsonSchema/Constraints/NumberConstraint.php +++ b/src/JsonSchema/Constraints/NumberConstraint.php @@ -20,7 +20,7 @@ class NumberConstraint extends Constraint { /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$element, $schema = null, JsonPointer $path = null, $i = null) { @@ -28,40 +28,40 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i = if (isset($schema->exclusiveMinimum)) { if (isset($schema->minimum)) { if ($schema->exclusiveMinimum && $element <= $schema->minimum) { - $this->addError($path, "Must have a minimum value of " . $schema->minimum, 'exclusiveMinimum', array('minimum' => $schema->minimum,)); + $this->addError($path, 'Must have a minimum value of ' . $schema->minimum, 'exclusiveMinimum', array('minimum' => $schema->minimum)); } elseif ($element < $schema->minimum) { - $this->addError($path, "Must have a minimum value of " . $schema->minimum, 'minimum', array('minimum' => $schema->minimum,)); + $this->addError($path, 'Must have a minimum value of ' . $schema->minimum, 'minimum', array('minimum' => $schema->minimum)); } } else { - $this->addError($path, "Use of exclusiveMinimum requires presence of minimum", 'missingMinimum'); + $this->addError($path, 'Use of exclusiveMinimum requires presence of minimum', 'missingMinimum'); } } elseif (isset($schema->minimum) && $element < $schema->minimum) { - $this->addError($path, "Must have a minimum value of " . $schema->minimum, 'minimum', array('minimum' => $schema->minimum,)); + $this->addError($path, 'Must have a minimum value of ' . $schema->minimum, 'minimum', array('minimum' => $schema->minimum)); } // Verify maximum if (isset($schema->exclusiveMaximum)) { if (isset($schema->maximum)) { if ($schema->exclusiveMaximum && $element >= $schema->maximum) { - $this->addError($path, "Must have a maximum value of " . $schema->maximum, 'exclusiveMaximum', array('maximum' => $schema->maximum,)); + $this->addError($path, 'Must have a maximum value of ' . $schema->maximum, 'exclusiveMaximum', array('maximum' => $schema->maximum)); } elseif ($element > $schema->maximum) { - $this->addError($path, "Must have a maximum value of " . $schema->maximum, 'maximum', array('maximum' => $schema->maximum,)); + $this->addError($path, 'Must have a maximum value of ' . $schema->maximum, 'maximum', array('maximum' => $schema->maximum)); } } else { - $this->addError($path, "Use of exclusiveMaximum requires presence of maximum", 'missingMaximum'); + $this->addError($path, 'Use of exclusiveMaximum requires presence of maximum', 'missingMaximum'); } } elseif (isset($schema->maximum) && $element > $schema->maximum) { - $this->addError($path, "Must have a maximum value of " . $schema->maximum, 'maximum', array('maximum' => $schema->maximum,)); + $this->addError($path, 'Must have a maximum value of ' . $schema->maximum, 'maximum', array('maximum' => $schema->maximum)); } // Verify divisibleBy - Draft v3 if (isset($schema->divisibleBy) && $this->fmod($element, $schema->divisibleBy) != 0) { - $this->addError($path, "Is not divisible by " . $schema->divisibleBy, 'divisibleBy', array('divisibleBy' => $schema->divisibleBy,)); + $this->addError($path, 'Is not divisible by ' . $schema->divisibleBy, 'divisibleBy', array('divisibleBy' => $schema->divisibleBy)); } // Verify multipleOf - Draft v4 if (isset($schema->multipleOf) && $this->fmod($element, $schema->multipleOf) != 0) { - $this->addError($path, "Must be a multiple of " . $schema->multipleOf, 'multipleOf', array('multipleOf' => $schema->multipleOf,)); + $this->addError($path, 'Must be a multiple of ' . $schema->multipleOf, 'multipleOf', array('multipleOf' => $schema->multipleOf)); } $this->checkFormat($element, $schema, $path, $i); @@ -72,15 +72,15 @@ private function fmod($number1, $number2) $number1 = abs($number1); $modulus = fmod($number1, $number2); $precision = abs(0.0000000001); - $diff = (float)($modulus - $number2); + $diff = (float) ($modulus - $number2); if (-$precision < $diff && $diff < $precision) { return 0.0; } - $decimals1 = mb_strpos($number1, ".") ? mb_strlen($number1) - mb_strpos($number1, ".") - 1 : 0; - $decimals2 = mb_strpos($number2, ".") ? mb_strlen($number2) - mb_strpos($number2, ".") - 1 : 0; + $decimals1 = mb_strpos($number1, '.') ? mb_strlen($number1) - mb_strpos($number1, '.') - 1 : 0; + $decimals2 = mb_strpos($number2, '.') ? mb_strlen($number2) - mb_strpos($number2, '.') - 1 : 0; - return (float)round($modulus, max($decimals1, $decimals2)); + return (float) round($modulus, max($decimals1, $decimals2)); } } diff --git a/src/JsonSchema/Constraints/ObjectConstraint.php b/src/JsonSchema/Constraints/ObjectConstraint.php index 1b6a229a..5ea94f7d 100644 --- a/src/JsonSchema/Constraints/ObjectConstraint.php +++ b/src/JsonSchema/Constraints/ObjectConstraint.php @@ -19,10 +19,10 @@ */ class ObjectConstraint extends Constraint { - /** - * {@inheritDoc} - */ - public function check(&$element, $definition = null, JsonPointer $path = null, $additionalProp = null, $patternProperties = null) + /** + * {@inheritdoc} + */ + public function check(&$element, $definition = null, JsonPointer $path = null, $additionalProp = null, $patternProperties = null) { if ($element instanceof UndefinedConstraint) { return; @@ -44,7 +44,7 @@ public function check(&$element, $definition = null, JsonPointer $path = null, $ public function validatePatternProperties($element, JsonPointer $path = null, $patternProperties) { - $try = array('/','#','+','~','%'); + $try = array('/', '#', '+', '~', '%'); $matches = array(); foreach ($patternProperties as $pregex => $schema) { $delimiter = '/'; @@ -56,17 +56,18 @@ public function validatePatternProperties($element, JsonPointer $path = null, $p } // Validate the pattern before using it to test for matches - if (@preg_match($delimiter. $pregex . $delimiter . 'u', '') === false) { - $this->addError($path, 'The pattern "' . $pregex . '" is invalid', 'pregex', array('pregex' => $pregex,)); + if (@preg_match($delimiter . $pregex . $delimiter . 'u', '') === false) { + $this->addError($path, 'The pattern "' . $pregex . '" is invalid', 'pregex', array('pregex' => $pregex)); continue; } foreach ($element as $i => $value) { if (preg_match($delimiter . $pregex . $delimiter . 'u', $i)) { $matches[] = $i; - $this->checkUndefined($value, $schema ? : new \stdClass(), $path, $i); + $this->checkUndefined($value, $schema ?: new \stdClass(), $path, $i); } } } + return $matches; } @@ -88,7 +89,7 @@ public function validateElement($element, $matches, $objectDefinition = null, Js // no additional properties allowed if (!in_array($i, $matches) && $additionalProp === false && $this->inlineSchemaProperty !== $i && !$definition) { - $this->addError($path, "The property " . $i . " is not defined and the definition does not allow additional properties", 'additionalProp'); + $this->addError($path, 'The property ' . $i . ' is not defined and the definition does not allow additional properties', 'additionalProp'); } // additional properties defined @@ -103,7 +104,7 @@ public function validateElement($element, $matches, $objectDefinition = null, Js // property requires presence of another $require = $this->getProperty($definition, 'requires'); if ($require && !$this->getProperty($element, $require)) { - $this->addError($path, "The presence of the property " . $i . " requires that " . $require . " also be present", 'requires'); + $this->addError($path, 'The presence of the property ' . $i . ' requires that ' . $require . ' also be present', 'requires'); } $property = $this->getProperty($element, $i, $this->factory->createInstanceFor('undefined')); @@ -116,9 +117,9 @@ public function validateElement($element, $matches, $objectDefinition = null, Js /** * Validates the definition properties * - * @param \stdClass $element Element to validate - * @param \stdClass $objectDefinition ObjectConstraint definition - * @param JsonPointer|null $path Path? + * @param \stdClass $element Element to validate + * @param \stdClass $objectDefinition ObjectConstraint definition + * @param JsonPointer|null $path Path? */ public function validateDefinition(&$element, $objectDefinition = null, JsonPointer $path = null) { @@ -162,17 +163,18 @@ protected function &getProperty(&$element, $property, $fallback = null) * @param \stdClass $objectDefinition ObjectConstraint definition * @param JsonPointer|null $path Path to test? */ - protected function validateMinMaxConstraint($element, $objectDefinition, JsonPointer $path = null) { + protected function validateMinMaxConstraint($element, $objectDefinition, JsonPointer $path = null) + { // Verify minimum number of properties if (isset($objectDefinition->minProperties) && !is_object($objectDefinition->minProperties)) { if ($this->getTypeCheck()->propertyCount($element) < $objectDefinition->minProperties) { - $this->addError($path, "Must contain a minimum of " . $objectDefinition->minProperties . " properties", 'minProperties', array('minProperties' => $objectDefinition->minProperties,)); + $this->addError($path, 'Must contain a minimum of ' . $objectDefinition->minProperties . ' properties', 'minProperties', array('minProperties' => $objectDefinition->minProperties)); } } // Verify maximum number of properties if (isset($objectDefinition->maxProperties) && !is_object($objectDefinition->maxProperties)) { if ($this->getTypeCheck()->propertyCount($element) > $objectDefinition->maxProperties) { - $this->addError($path, "Must contain no more than " . $objectDefinition->maxProperties . " properties", 'maxProperties', array('maxProperties' => $objectDefinition->maxProperties,)); + $this->addError($path, 'Must contain no more than ' . $objectDefinition->maxProperties . ' properties', 'maxProperties', array('maxProperties' => $objectDefinition->maxProperties)); } } } diff --git a/src/JsonSchema/Constraints/SchemaConstraint.php b/src/JsonSchema/Constraints/SchemaConstraint.php index 8a2c6f34..c33fe8ca 100644 --- a/src/JsonSchema/Constraints/SchemaConstraint.php +++ b/src/JsonSchema/Constraints/SchemaConstraint.php @@ -9,8 +9,8 @@ namespace JsonSchema\Constraints; -use JsonSchema\Exception\InvalidArgumentException; use JsonSchema\Entity\JsonPointer; +use JsonSchema\Exception\InvalidArgumentException; /** * The SchemaConstraint Constraints, validates an element against a given schema @@ -21,9 +21,10 @@ class SchemaConstraint extends Constraint { /** - * {@inheritDoc} + * {@inheritdoc} */ - public function check(&$element, $schema = null, JsonPointer $path = null, $i = null){ + public function check(&$element, $schema = null, JsonPointer $path = null, $i = null) + { if ($schema !== null) { // passed schema $this->checkUndefined($element, $schema, $path, $i); diff --git a/src/JsonSchema/Constraints/StringConstraint.php b/src/JsonSchema/Constraints/StringConstraint.php index 3b83023a..5b15de7a 100644 --- a/src/JsonSchema/Constraints/StringConstraint.php +++ b/src/JsonSchema/Constraints/StringConstraint.php @@ -20,27 +20,27 @@ class StringConstraint extends Constraint { /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$element, $schema = null, JsonPointer $path = null, $i = null) { // Verify maxLength if (isset($schema->maxLength) && $this->strlen($element) > $schema->maxLength) { - $this->addError($path, "Must be at most " . $schema->maxLength . " characters long", 'maxLength', array( + $this->addError($path, 'Must be at most ' . $schema->maxLength . ' characters long', 'maxLength', array( 'maxLength' => $schema->maxLength, )); } //verify minLength if (isset($schema->minLength) && $this->strlen($element) < $schema->minLength) { - $this->addError($path, "Must be at least " . $schema->minLength . " characters long", 'minLength', array( + $this->addError($path, 'Must be at least ' . $schema->minLength . ' characters long', 'minLength', array( 'minLength' => $schema->minLength, )); } // Verify a regex pattern if (isset($schema->pattern) && !preg_match('#' . str_replace('#', '\\#', $schema->pattern) . '#u', $element)) { - $this->addError($path, "Does not match the regex pattern " . $schema->pattern, 'pattern', array( + $this->addError($path, 'Does not match the regex pattern ' . $schema->pattern, 'pattern', array( 'pattern' => $schema->pattern, )); } @@ -52,8 +52,8 @@ private function strlen($string) { if (extension_loaded('mbstring')) { return mb_strlen($string, mb_detect_encoding($string)); - } else { - return strlen($string); } + + return strlen($string); } } diff --git a/src/JsonSchema/Constraints/TypeCheck/LooseTypeCheck.php b/src/JsonSchema/Constraints/TypeCheck/LooseTypeCheck.php index 7499c2e3..4818bf6d 100644 --- a/src/JsonSchema/Constraints/TypeCheck/LooseTypeCheck.php +++ b/src/JsonSchema/Constraints/TypeCheck/LooseTypeCheck.php @@ -54,6 +54,6 @@ public static function propertyCount($value) */ private static function isAssociativeArray($arr) { - return (array_keys($arr) !== range(0, count($arr) - 1)); + return array_keys($arr) !== range(0, count($arr) - 1); } } diff --git a/src/JsonSchema/Constraints/TypeConstraint.php b/src/JsonSchema/Constraints/TypeConstraint.php index 0ee33a29..0ef32843 100644 --- a/src/JsonSchema/Constraints/TypeConstraint.php +++ b/src/JsonSchema/Constraints/TypeConstraint.php @@ -9,8 +9,8 @@ namespace JsonSchema\Constraints; -use JsonSchema\Exception\InvalidArgumentException; use JsonSchema\Entity\JsonPointer; +use JsonSchema\Exception\InvalidArgumentException; use UnexpectedValueException as StandardUnexpectedValueException; /** @@ -24,7 +24,7 @@ class TypeConstraint extends Constraint /** * @var array|string[] type wordings for validation error messages */ - static $wording = array( + public static $wording = array( 'integer' => 'an integer', 'number' => 'a number', 'boolean' => 'a boolean', @@ -32,12 +32,12 @@ class TypeConstraint extends Constraint 'array' => 'an array', 'string' => 'a string', 'null' => 'a null', - 'any' => NULL, // validation of 'any' is always true so is not needed in message wording - 0 => NULL, // validation of a false-y value is always true, so not needed as well + 'any' => null, // validation of 'any' is always true so is not needed in message wording + 0 => null, // validation of a false-y value is always true, so not needed as well ); /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$value = null, $schema = null, JsonPointer $path = null, $i = null) { @@ -49,6 +49,7 @@ public function check(&$value = null, $schema = null, JsonPointer $path = null, $this->validateTypesArray($value, $type, $wording, $isValid, $path); } elseif (is_object($type)) { $this->checkUndefined($value, $type, $path); + return; } else { $isValid = $this->validateType($value, $type); @@ -59,8 +60,8 @@ public function check(&$value = null, $schema = null, JsonPointer $path = null, $this->validateTypeNameWording($type); $wording[] = self::$wording[$type]; } - $this->addError($path, ucwords(gettype($value)) . " value found, but " . - $this->implodeWith($wording, ', ', 'or') . " is required", 'type'); + $this->addError($path, ucwords(gettype($value)) . ' value found, but ' . + $this->implodeWith($wording, ', ', 'or') . ' is required', 'type'); } } @@ -69,13 +70,14 @@ public function check(&$value = null, $schema = null, JsonPointer $path = null, * of $isValid to true, if at least one $type mateches the type of $value or the value * passed as $isValid is already true. * - * @param mixed $value Value to validate - * @param array $type TypeConstraints to check agains + * @param mixed $value Value to validate + * @param array $type TypeConstraints to check agains * @param array $validTypesWording An array of wordings of the valid types of the array $type - * @param boolean $isValid The current validation value + * @param bool $isValid The current validation value * @param $path */ - protected function validateTypesArray(&$value, array $type, &$validTypesWording, &$isValid, $path) { + protected function validateTypesArray(&$value, array $type, &$validTypesWording, &$isValid, $path) + { foreach ($type as $tp) { // $tp can be an object, if it's a schema instead of a simple type, validate it // with a new type constraint @@ -86,14 +88,14 @@ protected function validateTypesArray(&$value, array $type, &$validTypesWording, $subSchema->type = $tp; $validator->check($value, $subSchema, $path, null); $error = $validator->getErrors(); - $isValid = !(bool)$error; + $isValid = !(bool) $error; $validTypesWording[] = self::$wording['object']; } } else { - $this->validateTypeNameWording( $tp ); + $this->validateTypeNameWording($tp); $validTypesWording[] = self::$wording[$tp]; if (!$isValid) { - $isValid = $this->validateType( $value, $tp); + $isValid = $this->validateType($value, $tp); } } } @@ -104,18 +106,21 @@ protected function validateTypesArray(&$value, array $type, &$validTypesWording, * difference, that, if $listEnd isn't false, the last element delimiter is $listEnd instead of * $delimiter. * - * @param array $elements The elements to implode + * @param array $elements The elements to implode * @param string $delimiter The delimiter to use - * @param bool $listEnd The last delimiter to use (defaults to $delimiter) + * @param bool $listEnd The last delimiter to use (defaults to $delimiter) + * * @return string */ - protected function implodeWith(array $elements, $delimiter = ', ', $listEnd = false) { + protected function implodeWith(array $elements, $delimiter = ', ', $listEnd = false) + { if ($listEnd === false || !isset($elements[1])) { return implode($delimiter, $elements); } $lastElement = array_slice($elements, -1); $firsElements = join($delimiter, array_slice($elements, 0, -1)); $implodedElements = array_merge(array($firsElements), $lastElement); + return join(" $listEnd ", $implodedElements); } @@ -127,11 +132,12 @@ protected function implodeWith(array $elements, $delimiter = ', ', $listEnd = fa * * @throws StandardUnexpectedValueException */ - protected function validateTypeNameWording( $type) { + protected function validateTypeNameWording($type) + { if (!isset(self::$wording[$type])) { throw new StandardUnexpectedValueException( sprintf( - "No wording for %s available, expected wordings are: [%s]", + 'No wording for %s available, expected wordings are: [%s]', var_export($type, true), implode(', ', array_filter(self::$wording))) ); @@ -143,10 +149,10 @@ protected function validateTypeNameWording( $type) { * * @param mixed $value Value to validate * @param string $type TypeConstraint to check against - * - * @return boolean * * @throws InvalidArgumentException + * + * @return bool */ protected function validateType(&$value, $type) { @@ -173,6 +179,7 @@ protected function validateType(&$value, $type) if ($coerce) { $value = $this->toInteger($value); } + return is_int($value); } @@ -180,6 +187,7 @@ protected function validateType(&$value, $type) if ($coerce) { $value = $this->toNumber($value); } + return is_numeric($value) && !is_string($value); } @@ -187,6 +195,7 @@ protected function validateType(&$value, $type) if ($coerce) { $value = $this->toBoolean($value); } + return is_bool($value); } @@ -207,16 +216,18 @@ protected function validateType(&$value, $type) /** * Converts a value to boolean. For example, "true" becomes true. + * * @param $value The value to convert to boolean + * * @return bool|mixed */ protected function toBoolean($value) { - if($value === "true"){ + if ($value === 'true') { return true; } - if($value === "false"){ + if ($value === 'false') { return false; } @@ -226,12 +237,13 @@ protected function toBoolean($value) /** * Converts a numeric string to a number. For example, "4" becomes 4. * - * @param mixed $value The value to convert to a number. + * @param mixed $value the value to convert to a number + * * @return int|float|mixed */ protected function toNumber($value) { - if(is_numeric($value)) { + if (is_numeric($value)) { return $value + 0; // cast to number } @@ -240,8 +252,8 @@ protected function toNumber($value) protected function toInteger($value) { - if(is_numeric($value) && (int)$value == $value) { - return (int)$value; // cast to number + if (is_numeric($value) && (int) $value == $value) { + return (int) $value; // cast to number } return $value; diff --git a/src/JsonSchema/Constraints/UndefinedConstraint.php b/src/JsonSchema/Constraints/UndefinedConstraint.php index 51464c5d..2b0688ec 100644 --- a/src/JsonSchema/Constraints/UndefinedConstraint.php +++ b/src/JsonSchema/Constraints/UndefinedConstraint.php @@ -9,8 +9,8 @@ namespace JsonSchema\Constraints; -use JsonSchema\Uri\UriResolver; use JsonSchema\Entity\JsonPointer; +use JsonSchema\Uri\UriResolver; /** * The UndefinedConstraint Constraints @@ -21,7 +21,7 @@ class UndefinedConstraint extends Constraint { /** - * {@inheritDoc} + * {@inheritdoc} */ public function check(&$value, $schema = null, JsonPointer $path = null, $i = null) { @@ -91,7 +91,7 @@ public function validateTypes(&$value, $schema = null, JsonPointer $path, $i = n * @param JsonPointer $path * @param string $i */ - protected function validateCommonProperties(&$value, $schema = null, JsonPointer $path, $i = "") + protected function validateCommonProperties(&$value, $schema = null, JsonPointer $path, $i = '') { // if it extends another schema, it must pass that schema as well if (isset($schema->extends)) { @@ -109,27 +109,27 @@ protected function validateCommonProperties(&$value, $schema = null, JsonPointer // Verify required values if ($this->getTypeCheck()->isObject($value)) { - if (!($value instanceof UndefinedConstraint) && isset($schema->required) && is_array($schema->required)) { + if (!($value instanceof self) && isset($schema->required) && is_array($schema->required)) { // Draft 4 - Required is an array of strings - e.g. "required": ["foo", ...] foreach ($schema->required as $required) { if (!$this->getTypeCheck()->propertyExists($value, $required)) { $this->addError( $this->incrementPath($path ?: new JsonPointer(''), $required), - "The property " . $required . " is required", + 'The property ' . $required . ' is required', 'required' ); } } } elseif (isset($schema->required) && !is_array($schema->required)) { // Draft 3 - Required attribute - e.g. "foo": {"type": "string", "required": true} - if ($schema->required && $value instanceof UndefinedConstraint) { - $this->addError($path, "Is missing and it is required", 'required'); + if ($schema->required && $value instanceof self) { + $this->addError($path, 'Is missing and it is required', 'required'); } } } // Verify type - if (!($value instanceof UndefinedConstraint)) { + if (!($value instanceof self)) { $this->checkType($value, $schema, $path, $i); } @@ -143,7 +143,7 @@ protected function validateCommonProperties(&$value, $schema = null, JsonPointer // if no new errors were raised it must be a disallowed value if (count($this->getErrors()) == count($initErrors)) { - $this->addError($path, "Disallowed value was matched", 'disallow'); + $this->addError($path, 'Disallowed value was matched', 'disallow'); } else { $this->errors = $initErrors; } @@ -155,7 +155,7 @@ protected function validateCommonProperties(&$value, $schema = null, JsonPointer // if no new errors were raised then the instance validated against the "not" schema if (count($this->getErrors()) == count($initErrors)) { - $this->addError($path, "Matched a schema which it should not", 'not'); + $this->addError($path, 'Matched a schema which it should not', 'not'); } else { $this->errors = $initErrors; } @@ -175,10 +175,10 @@ protected function validateCommonProperties(&$value, $schema = null, JsonPointer * @param JsonPointer $path * @param string $i */ - protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i = "") + protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i = '') { // Verify type - if ($value instanceof UndefinedConstraint) { + if ($value instanceof self) { return; } @@ -190,7 +190,7 @@ protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i $isValid = $isValid && (count($this->getErrors()) == count($initErrors)); } if (!$isValid) { - $this->addError($path, "Failed to match all schemas", 'allOf'); + $this->addError($path, 'Failed to match all schemas', 'allOf'); } } @@ -205,7 +205,7 @@ protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i } } if (!$isValid) { - $this->addError($path, "Failed to match at least one schema", 'anyOf'); + $this->addError($path, 'Failed to match at least one schema', 'anyOf'); } else { $this->errors = $startErrors; } @@ -225,7 +225,7 @@ protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i } if ($matchedSchemas !== 1) { $this->addErrors(array_merge($allErrors, $startErrors)); - $this->addError($path, "Failed to match exactly one schema", 'oneOf'); + $this->addError($path, 'Failed to match exactly one schema', 'oneOf'); } else { $this->errors = $startErrors; } @@ -240,7 +240,7 @@ protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i * @param JsonPointer $path * @param string $i */ - protected function validateDependencies($value, $dependencies, JsonPointer $path, $i = "") + protected function validateDependencies($value, $dependencies, JsonPointer $path, $i = '') { foreach ($dependencies as $key => $dependency) { if ($this->getTypeCheck()->propertyExists($value, $key)) { diff --git a/src/JsonSchema/Entity/JsonPointer.php b/src/JsonSchema/Entity/JsonPointer.php index 00e14e09..31c753ba 100644 --- a/src/JsonSchema/Entity/JsonPointer.php +++ b/src/JsonSchema/Entity/JsonPointer.php @@ -11,6 +11,7 @@ /** * @package JsonSchema\Entity + * * @author Joost Nijhuis */ class JsonPointer @@ -23,6 +24,7 @@ class JsonPointer /** * @param string $value + * * @throws \InvalidArgumentException when $value is not a string */ public function __construct($value) @@ -40,6 +42,7 @@ public function __construct($value) /** * @param string $propertyPathString + * * @return string[] */ private function decodePropertyPaths($propertyPathString) @@ -68,6 +71,7 @@ private function encodePropertyPaths() /** * @param string $path + * * @return string */ private function decodePath($path) @@ -77,6 +81,7 @@ private function decodePath($path) /** * @param string $path + * * @return string */ private function encodePath($path) @@ -102,12 +107,14 @@ public function getPropertyPaths() /** * @param array $propertyPaths + * * @return JsonPointer */ public function withPropertyPaths(array $propertyPaths) { $new = clone $this; $new->propertyPaths = $propertyPaths; + return $new; } diff --git a/src/JsonSchema/Exception/ExceptionInterface.php b/src/JsonSchema/Exception/ExceptionInterface.php index 14d532a5..439bd277 100644 --- a/src/JsonSchema/Exception/ExceptionInterface.php +++ b/src/JsonSchema/Exception/ExceptionInterface.php @@ -4,5 +4,4 @@ interface ExceptionInterface { - } diff --git a/src/JsonSchema/Exception/InvalidArgumentException.php b/src/JsonSchema/Exception/InvalidArgumentException.php index ac37135d..cabfa680 100644 --- a/src/JsonSchema/Exception/InvalidArgumentException.php +++ b/src/JsonSchema/Exception/InvalidArgumentException.php @@ -14,4 +14,4 @@ */ class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { -} \ No newline at end of file +} diff --git a/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.php b/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.php index 93cc97e5..bcac26f4 100644 --- a/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.php +++ b/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.php @@ -13,5 +13,5 @@ * Wrapper for the InvalidSchemaMediaType */ class InvalidSchemaMediaTypeException extends RuntimeException -{ -} \ No newline at end of file +{ +} diff --git a/src/JsonSchema/Exception/JsonDecodingException.php b/src/JsonSchema/Exception/JsonDecodingException.php index a755626e..c7719828 100644 --- a/src/JsonSchema/Exception/JsonDecodingException.php +++ b/src/JsonSchema/Exception/JsonDecodingException.php @@ -37,4 +37,4 @@ public function __construct($code = JSON_ERROR_NONE, \Exception $previous = null } parent::__construct($message, $code, $previous); } -} \ No newline at end of file +} diff --git a/src/JsonSchema/Exception/ResourceNotFoundException.php b/src/JsonSchema/Exception/ResourceNotFoundException.php index 3341a90a..e639ba32 100644 --- a/src/JsonSchema/Exception/ResourceNotFoundException.php +++ b/src/JsonSchema/Exception/ResourceNotFoundException.php @@ -14,4 +14,4 @@ */ class ResourceNotFoundException extends RuntimeException { -} \ No newline at end of file +} diff --git a/src/JsonSchema/Exception/RuntimeException.php b/src/JsonSchema/Exception/RuntimeException.php index 3a4d3f91..8a2a9006 100644 --- a/src/JsonSchema/Exception/RuntimeException.php +++ b/src/JsonSchema/Exception/RuntimeException.php @@ -14,4 +14,4 @@ */ class RuntimeException extends \RuntimeException implements ExceptionInterface { -} \ No newline at end of file +} diff --git a/src/JsonSchema/Exception/UnresolvableJsonPointerException.php b/src/JsonSchema/Exception/UnresolvableJsonPointerException.php index 44c562ed..5f49e2f0 100644 --- a/src/JsonSchema/Exception/UnresolvableJsonPointerException.php +++ b/src/JsonSchema/Exception/UnresolvableJsonPointerException.php @@ -11,6 +11,7 @@ /** * @package JsonSchema\Exception + * * @author Joost Nijhuis */ class UnresolvableJsonPointerException extends InvalidArgumentException diff --git a/src/JsonSchema/Exception/UriResolverException.php b/src/JsonSchema/Exception/UriResolverException.php index f9e7f286..13b73033 100644 --- a/src/JsonSchema/Exception/UriResolverException.php +++ b/src/JsonSchema/Exception/UriResolverException.php @@ -14,4 +14,4 @@ */ class UriResolverException extends RuntimeException { -} \ No newline at end of file +} diff --git a/src/JsonSchema/Iterator/ObjectIterator.php b/src/JsonSchema/Iterator/ObjectIterator.php index 61bf5be6..c459713b 100644 --- a/src/JsonSchema/Iterator/ObjectIterator.php +++ b/src/JsonSchema/Iterator/ObjectIterator.php @@ -11,6 +11,7 @@ /** * @package JsonSchema\Iterator + * * @author Joost Nijhuis */ class ObjectIterator implements \Iterator, \Countable @@ -106,6 +107,7 @@ private function initialize() /** * @param object $object + * * @return array */ private function buildDataFromObject($object) @@ -116,7 +118,6 @@ private function buildDataFromObject($object) $stack->push($object); while (!$stack->isEmpty()) { - $current = $stack->pop(); if (is_object($current)) { array_push($result, $current); @@ -134,6 +135,7 @@ private function buildDataFromObject($object) /** * @param object|array $item + * * @return array */ private function getDataFromItem($item) diff --git a/src/JsonSchema/Rfc3339.php b/src/JsonSchema/Rfc3339.php index 62509aa5..fb2eb7d5 100644 --- a/src/JsonSchema/Rfc3339.php +++ b/src/JsonSchema/Rfc3339.php @@ -10,6 +10,7 @@ class Rfc3339 * Try creating a DateTime instance * * @param string $string + * * @return \DateTime|null */ public static function createFromString($string) diff --git a/src/JsonSchema/SchemaStorage.php b/src/JsonSchema/SchemaStorage.php index 03d28d10..6450572e 100644 --- a/src/JsonSchema/SchemaStorage.php +++ b/src/JsonSchema/SchemaStorage.php @@ -18,8 +18,8 @@ public function __construct( UriRetrieverInterface $uriRetriever = null, UriResolverInterface $uriResolver = null ) { - $this->uriRetriever = $uriRetriever ?: new UriRetriever; - $this->uriResolver = $uriResolver ?: new UriResolver; + $this->uriRetriever = $uriRetriever ?: new UriRetriever(); + $this->uriResolver = $uriResolver ?: new UriResolver(); } /** @@ -50,7 +50,7 @@ public function addSchema($id, $schema = null) foreach ($objectIterator as $toResolveSchema) { if (property_exists($toResolveSchema, '$ref') && is_string($toResolveSchema->{'$ref'})) { $jsonPointer = new JsonPointer($this->uriResolver->resolve($toResolveSchema->{'$ref'}, $id)); - $toResolveSchema->{'$ref'} = (string)$jsonPointer; + $toResolveSchema->{'$ref'} = (string) $jsonPointer; } } $this->schemas[$id] = $schema; diff --git a/src/JsonSchema/SchemaStorageInterface.php b/src/JsonSchema/SchemaStorageInterface.php index 0f67478b..ddaf6633 100644 --- a/src/JsonSchema/SchemaStorageInterface.php +++ b/src/JsonSchema/SchemaStorageInterface.php @@ -6,6 +6,7 @@ interface SchemaStorageInterface { /** * Adds schema with given identifier + * * @param string $id * @param object $schema */ @@ -13,21 +14,27 @@ public function addSchema($id, $schema = null); /** * Returns schema for given identifier, or null if it does not exist + * * @param string $id + * * @return object */ public function getSchema($id); /** * Returns schema for given reference with all sub-references resolved + * * @param string $ref + * * @return object */ public function resolveRef($ref); /** * Returns schema referenced by '$ref' property + * * @param mixed $refSchema + * * @return object */ public function resolveRefSchema($refSchema); diff --git a/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php b/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php index 5dfb9533..9ab24b95 100644 --- a/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php +++ b/src/JsonSchema/Uri/Retrievers/AbstractRetriever.php @@ -1,25 +1,30 @@ */ abstract class AbstractRetriever implements UriRetrieverInterface { /** * Media content type + * * @var string */ protected $contentType; /** - * {@inheritDoc} + * {@inheritdoc} + * * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::getContentType() */ public function getContentType() diff --git a/src/JsonSchema/Uri/Retrievers/Curl.php b/src/JsonSchema/Uri/Retrievers/Curl.php index cd8414f3..a4125aa6 100644 --- a/src/JsonSchema/Uri/Retrievers/Curl.php +++ b/src/JsonSchema/Uri/Retrievers/Curl.php @@ -23,12 +23,13 @@ class Curl extends AbstractRetriever public function __construct() { if (!function_exists('curl_init')) { - throw new \RuntimeException("cURL not installed"); + throw new \RuntimeException('cURL not installed'); } } /** - * {@inheritDoc} + * {@inheritdoc} + * * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve() */ public function retrieve($uri) @@ -64,7 +65,8 @@ private function fetchMessageBody($response) /** * @param string $response cURL HTTP response - * @return boolean Whether the Content-Type header was found or not + * + * @return bool Whether the Content-Type header was found or not */ protected function fetchContentType($response) { @@ -76,4 +78,4 @@ protected function fetchContentType($response) return false; } -} \ No newline at end of file +} diff --git a/src/JsonSchema/Uri/Retrievers/FileGetContents.php b/src/JsonSchema/Uri/Retrievers/FileGetContents.php index f2e73c3b..7f0c399a 100644 --- a/src/JsonSchema/Uri/Retrievers/FileGetContents.php +++ b/src/JsonSchema/Uri/Retrievers/FileGetContents.php @@ -21,7 +21,8 @@ class FileGetContents extends AbstractRetriever protected $messageBody; /** - * {@inheritDoc} + * {@inheritdoc} + * * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve() */ public function retrieve($uri) @@ -38,13 +39,13 @@ public function retrieve($uri) } if (false === $response) { - throw new ResourceNotFoundException('JSON schema not found at '.$uri); + throw new ResourceNotFoundException('JSON schema not found at ' . $uri); } if ($response == '' && substr($uri, 0, 7) == 'file://' && substr($uri, -1) == '/' ) { - throw new ResourceNotFoundException('JSON schema not found at '.$uri); + throw new ResourceNotFoundException('JSON schema not found at ' . $uri); } $this->messageBody = $response; @@ -60,7 +61,8 @@ public function retrieve($uri) /** * @param array $headers HTTP Response Headers - * @return boolean Whether the Content-Type header was found or not + * + * @return bool Whether the Content-Type header was found or not */ private function fetchContentType(array $headers) { @@ -75,6 +77,7 @@ private function fetchContentType(array $headers) /** * @param string $header + * * @return string|null */ protected static function getContentTypeMatchInHeader($header) diff --git a/src/JsonSchema/Uri/Retrievers/PredefinedArray.php b/src/JsonSchema/Uri/Retrievers/PredefinedArray.php index 7652c424..a663d341 100644 --- a/src/JsonSchema/Uri/Retrievers/PredefinedArray.php +++ b/src/JsonSchema/Uri/Retrievers/PredefinedArray.php @@ -20,6 +20,7 @@ class PredefinedArray extends AbstractRetriever { /** * Contains schemas as URI => JSON + * * @var array */ private $schemas; @@ -27,8 +28,8 @@ class PredefinedArray extends AbstractRetriever /** * Constructor * - * @param array $schemas - * @param string $contentType + * @param array $schemas + * @param string $contentType */ public function __construct(array $schemas, $contentType = Validator::SCHEMA_MEDIA_TYPE) { @@ -37,7 +38,8 @@ public function __construct(array $schemas, $contentType = Validator::SCHEMA_MED } /** - * {@inheritDoc} + * {@inheritdoc} + * * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve() */ public function retrieve($uri) diff --git a/src/JsonSchema/Uri/Retrievers/UriRetrieverInterface.php b/src/JsonSchema/Uri/Retrievers/UriRetrieverInterface.php index c3249989..2cc40cf2 100644 --- a/src/JsonSchema/Uri/Retrievers/UriRetrieverInterface.php +++ b/src/JsonSchema/Uri/Retrievers/UriRetrieverInterface.php @@ -11,22 +11,26 @@ /** * Interface for URI retrievers - * - * @author Sander Coolen + * + * @author Sander Coolen */ interface UriRetrieverInterface { /** * Retrieve a schema from the specified URI + * * @param string $uri URI that resolves to a JSON schema + * * @throws \JsonSchema\Exception\ResourceNotFoundException + * * @return mixed string|null */ public function retrieve($uri); - + /** * Get media content type + * * @return string */ public function getContentType(); -} \ No newline at end of file +} diff --git a/src/JsonSchema/Uri/UriResolver.php b/src/JsonSchema/Uri/UriResolver.php index a4a63237..7d6e793d 100644 --- a/src/JsonSchema/Uri/UriResolver.php +++ b/src/JsonSchema/Uri/UriResolver.php @@ -14,16 +14,17 @@ /** * Resolves JSON Schema URIs - * - * @author Sander Coolen + * + * @author Sander Coolen */ class UriResolver implements UriResolverInterface { /** * Parses a URI into five main components - * + * * @param string $uri - * @return array + * + * @return array */ public function parse($uri) { @@ -36,39 +37,40 @@ public function parse($uri) 'authority' => $match[4], 'path' => $match[5] ); - } + } if (7 < count($match)) { $components['query'] = $match[7]; } if (9 < count($match)) { $components['fragment'] = $match[9]; } - + return $components; } - + /** * Builds a URI based on n array with the main components - * + * * @param array $components - * @return string + * + * @return string */ public function generate(array $components) { - $uri = $components['scheme'] . '://' + $uri = $components['scheme'] . '://' . $components['authority'] . $components['path']; - + if (array_key_exists('query', $components)) { $uri .= $components['query']; } if (array_key_exists('fragment', $components)) { $uri .= '#' . $components['fragment']; } - + return $uri; } - + /** * {@inheritdoc} */ @@ -80,13 +82,13 @@ public function resolve($uri, $baseUri = null) $components = $this->parse($uri); $path = $components['path']; - - if (! empty($components['scheme'])) { + + if (!empty($components['scheme'])) { return $uri; } $baseComponents = $this->parse($baseUri); $basePath = $baseComponents['path']; - + $baseComponents['path'] = self::combineRelativePathWithBasePath($path, $basePath); if (isset($components['fragment'])) { $baseComponents['fragment'] = $components['fragment']; @@ -94,14 +96,16 @@ public function resolve($uri, $baseUri = null) return $this->generate($baseComponents); } - + /** * Tries to glue a relative path onto an absolute one * * @param string $relativePath * @param string $basePath - * @return string Merged path + * * @throws UriResolverException + * + * @return string Merged path */ public static function combineRelativePathWithBasePath($relativePath, $basePath) { @@ -109,7 +113,7 @@ public static function combineRelativePathWithBasePath($relativePath, $basePath) if ($relativePath == '') { return $basePath; } - if ($relativePath{0} == '/') { + if ($relativePath[0] == '/') { return $relativePath; } @@ -131,24 +135,26 @@ public static function combineRelativePathWithBasePath($relativePath, $basePath) * Normalizes a URI path component by removing dot-slash and double slashes * * @param string $path + * * @return string */ private static function normalizePath($path) { $path = preg_replace('|((?parse($uri); - + return !empty($components); } } diff --git a/src/JsonSchema/Uri/UriRetriever.php b/src/JsonSchema/Uri/UriRetriever.php index b2445a7e..ebb7eb33 100644 --- a/src/JsonSchema/Uri/UriRetriever.php +++ b/src/JsonSchema/Uri/UriRetriever.php @@ -9,13 +9,13 @@ namespace JsonSchema\Uri; +use JsonSchema\Exception\InvalidSchemaMediaTypeException; +use JsonSchema\Exception\JsonDecodingException; +use JsonSchema\Exception\ResourceNotFoundException; use JsonSchema\Uri\Retrievers\FileGetContents; use JsonSchema\Uri\Retrievers\UriRetrieverInterface; use JsonSchema\UriRetrieverInterface as BaseUriRetrieverInterface; use JsonSchema\Validator; -use JsonSchema\Exception\InvalidSchemaMediaTypeException; -use JsonSchema\Exception\JsonDecodingException; -use JsonSchema\Exception\ResourceNotFoundException; /** * Retrieves JSON Schema URIs @@ -31,6 +31,7 @@ class UriRetriever implements BaseUriRetrieverInterface /** * @var array|object[] + * * @see loadSchema */ private $schemaCache = array(); @@ -39,7 +40,8 @@ class UriRetriever implements BaseUriRetrieverInterface * Guarantee the correct media type was encountered * * @param UriRetrieverInterface $uriRetriever - * @param string $uri + * @param string $uri + * * @return bool|void */ public function confirmMediaType($uriRetriever, $uri) @@ -74,7 +76,7 @@ public function confirmMediaType($uriRetriever, $uri) public function getUriRetriever() { if (is_null($this->uriRetriever)) { - $this->setUriRetriever(new FileGetContents); + $this->setUriRetriever(new FileGetContents()); } return $this->uriRetriever; @@ -88,10 +90,11 @@ public function getUriRetriever() * the first object then the 'to' and 'object' properties. * * @param object $jsonSchema JSON Schema contents - * @param string $uri JSON Schema URI - * @return object JSON Schema after walking down the fragment pieces + * @param string $uri JSON Schema URI * * @throws ResourceNotFoundException + * + * @return object JSON Schema after walking down the fragment pieces */ public function resolvePointer($jsonSchema, $uri) { @@ -104,10 +107,10 @@ public function resolvePointer($jsonSchema, $uri) $path = explode('/', $parsed['fragment']); while ($path) { $pathElement = array_shift($path); - if (! empty($pathElement)) { + if (!empty($pathElement)) { $pathElement = str_replace('~1', '/', $pathElement); $pathElement = str_replace('~0', '~', $pathElement); - if (! empty($jsonSchema->$pathElement)) { + if (!empty($jsonSchema->$pathElement)) { $jsonSchema = $jsonSchema->$pathElement; } else { throw new ResourceNotFoundException( @@ -116,7 +119,7 @@ public function resolvePointer($jsonSchema, $uri) ); } - if (! is_object($jsonSchema)) { + if (!is_object($jsonSchema)) { throw new ResourceNotFoundException( 'Fragment part "' . $pathElement . '" is no object ' . ' in ' . $uri @@ -187,6 +190,7 @@ protected function loadSchema($fetchUri) * Set the URI Retriever * * @param UriRetrieverInterface $uriRetriever + * * @return $this for chaining */ public function setUriRetriever(UriRetrieverInterface $uriRetriever) @@ -200,6 +204,7 @@ public function setUriRetriever(UriRetrieverInterface $uriRetriever) * Parses a URI into five main components * * @param string $uri + * * @return array */ public function parse($uri) @@ -230,6 +235,7 @@ public function parse($uri) * Builds a URI based on n array with the main components * * @param array $components + * * @return string */ public function generate(array $components) @@ -252,8 +258,9 @@ public function generate(array $components) /** * Resolves a URI * - * @param string $uri Absolute or relative + * @param string $uri Absolute or relative * @param string $baseUri Optional base URI + * * @return string */ public function resolve($uri, $baseUri = null) @@ -275,7 +282,8 @@ public function resolve($uri, $baseUri = null) /** * @param string $uri - * @return boolean + * + * @return bool */ public function isValid($uri) { diff --git a/src/JsonSchema/UriResolverInterface.php b/src/JsonSchema/UriResolverInterface.php index 1386c187..4eb50c03 100644 --- a/src/JsonSchema/UriResolverInterface.php +++ b/src/JsonSchema/UriResolverInterface.php @@ -17,8 +17,9 @@ interface UriResolverInterface /** * Resolves a URI * - * @param string $uri Absolute or relative + * @param string $uri Absolute or relative * @param null|string $baseUri Optional base URI + * * @return string Absolute URI */ public function resolve($uri, $baseUri = null); diff --git a/src/JsonSchema/UriRetrieverInterface.php b/src/JsonSchema/UriRetrieverInterface.php index 3b683f9e..94ad0cba 100644 --- a/src/JsonSchema/UriRetrieverInterface.php +++ b/src/JsonSchema/UriRetrieverInterface.php @@ -17,8 +17,9 @@ interface UriRetrieverInterface /** * Retrieve a URI * - * @param string $uri JSON Schema URI + * @param string $uri JSON Schema URI * @param null|string $baseUri + * * @return object JSON Schema contents */ public function retrieve($uri, $baseUri = null); diff --git a/src/JsonSchema/Validator.php b/src/JsonSchema/Validator.php index 0fb62014..e2a919bc 100644 --- a/src/JsonSchema/Validator.php +++ b/src/JsonSchema/Validator.php @@ -9,8 +9,8 @@ namespace JsonSchema; -use JsonSchema\Constraints\Constraint; use JsonSchema\Constraints\BaseConstraint; +use JsonSchema\Constraints\Constraint; use JsonSchema\Exception\InvalidConfigException; /** @@ -18,6 +18,7 @@ * * @author Robert Schönthal * @author Bruno Prieto Reis + * * @see README.md */ class Validator extends BaseConstraint @@ -31,7 +32,7 @@ class Validator extends BaseConstraint * * Note that the first argument is passwd by reference, so you must pass in a variable. * - * {@inheritDoc} + * {@inheritdoc} */ public function validate(&$value, $schema = null, $checkMode = null) { diff --git a/tests/Constraints/BaseTestCase.php b/tests/Constraints/BaseTestCase.php index 07f5636f..75010e33 100644 --- a/tests/Constraints/BaseTestCase.php +++ b/tests/Constraints/BaseTestCase.php @@ -35,7 +35,7 @@ public function testInvalidCases($input, $schema, $checkMode = Constraint::CHECK $validator->validate($checkValue, $schema); if (array() !== $errors) { - $this->assertEquals($errors, $validator->getErrors(), print_r($validator->getErrors(),true)); + $this->assertEquals($errors, $validator->getErrors(), print_r($validator->getErrors(), true)); } $this->assertFalse($validator->isValid(), print_r($validator->getErrors(), true)); } @@ -88,7 +88,7 @@ public function testValidCasesUsingAssoc($input, $schema, $checkMode = Constrain } $schema = json_decode($schema); - $schemaStorage = new SchemaStorage($this->getUriRetrieverMock($schema), new UriResolver); + $schemaStorage = new SchemaStorage($this->getUriRetrieverMock($schema), new UriResolver()); $schema = $schemaStorage->getSchema('http://www.my-domain.com/schema.json'); $value = json_decode($input, true); diff --git a/tests/Constraints/CoerciveTest.php b/tests/Constraints/CoerciveTest.php index b8d134d5..cb5c5518 100644 --- a/tests/Constraints/CoerciveTest.php +++ b/tests/Constraints/CoerciveTest.php @@ -48,25 +48,25 @@ public function testValidCoerceCases($input, $schema, $errors = array()) $validator = new Validator(new Factory($schemaStorage, null, $checkMode)); $value = json_decode($input); - $this->assertTrue(gettype($value->number) == "string"); - $this->assertTrue(gettype($value->integer) == "string"); - $this->assertTrue(gettype($value->boolean) == "string"); + $this->assertTrue(gettype($value->number) == 'string'); + $this->assertTrue(gettype($value->integer) == 'string'); + $this->assertTrue(gettype($value->boolean) == 'string'); $validator->validate($value, $schema, $checkMode); - $this->assertTrue(gettype($value->number) == "double"); - $this->assertTrue(gettype($value->integer) == "integer"); - $this->assertTrue(gettype($value->negativeInteger) == "integer"); - $this->assertTrue(gettype($value->boolean) == "boolean"); + $this->assertTrue(gettype($value->number) == 'double'); + $this->assertTrue(gettype($value->integer) == 'integer'); + $this->assertTrue(gettype($value->negativeInteger) == 'integer'); + $this->assertTrue(gettype($value->boolean) == 'boolean'); $this->assertTrue($value->number === 1.5); $this->assertTrue($value->integer === 1); $this->assertTrue($value->negativeInteger === -2); $this->assertTrue($value->boolean === true); - $this->assertTrue(gettype($value->multitype1) == "boolean"); - $this->assertTrue(gettype($value->multitype2) == "double"); - $this->assertTrue(gettype($value->multitype3) == "integer"); + $this->assertTrue(gettype($value->multitype1) == 'boolean'); + $this->assertTrue(gettype($value->multitype2) == 'double'); + $this->assertTrue(gettype($value->multitype3) == 'integer'); $this->assertTrue($value->number === 1.5); $this->assertTrue($value->integer === 1); @@ -189,7 +189,6 @@ public function getValidCoerceTests() ); } - public function getInvalidCoerceTests() { return array( diff --git a/tests/Constraints/DependenciesTest.php b/tests/Constraints/DependenciesTest.php index daf9177b..2e508218 100644 --- a/tests/Constraints/DependenciesTest.php +++ b/tests/Constraints/DependenciesTest.php @@ -145,4 +145,4 @@ public function getValidTests() ) ); } -} \ No newline at end of file +} diff --git a/tests/Constraints/FactoryTest.php b/tests/Constraints/FactoryTest.php index 59d3cf79..4f13bcf6 100644 --- a/tests/Constraints/FactoryTest.php +++ b/tests/Constraints/FactoryTest.php @@ -14,19 +14,25 @@ use JsonSchema\Entity\JsonPointer; use PHPUnit_Framework_TestCase as TestCase; - /** * Class MyBadConstraint + * * @package JsonSchema\Tests\Constraints */ -class MyBadConstraint {} +class MyBadConstraint +{ +} /** * Class MyStringConstraint + * * @package JsonSchema\Tests\Constraints */ -class MyStringConstraint extends Constraint { - public function check(&$value, $schema = null, JsonPointer $path = null, $i = null){} +class MyStringConstraint extends Constraint +{ + public function check(&$value, $schema = null, JsonPointer $path = null, $i = null) + { + } } class FactoryTest extends TestCase @@ -46,7 +52,6 @@ protected function setUp() * * @param string $constraintName * @param string $expectedClass - * @return void */ public function testCreateInstanceForConstraintName($constraintName, $expectedClass) { @@ -76,7 +81,6 @@ public function constraintNameProvider() * @dataProvider invalidConstraintNameProvider * * @param string $constraintName - * @return void */ public function testExceptionWhenCreateInstanceForInvalidConstraintName($constraintName) { @@ -84,34 +88,35 @@ public function testExceptionWhenCreateInstanceForInvalidConstraintName($constra $this->factory->createInstanceFor($constraintName); } - public function invalidConstraintNameProvider() { - return array( - array('invalidConstraintName'), - ); + public function invalidConstraintNameProvider() + { + return array( + array('invalidConstraintName'), + ); } /** - * @expectedException InvalidArgumentException + * @expectedException \JsonSchema\Exception\InvalidArgumentException */ public function testSetConstraintClassExistsCondition() { - $this->factory->setConstraintClass('string', 'SomeConstraint'); + $this->factory->setConstraintClass('string', 'SomeConstraint'); } /** - * @expectedException InvalidArgumentException + * @expectedException \JsonSchema\Exception\InvalidArgumentException */ public function testSetConstraintClassImplementsCondition() { - $this->factory->setConstraintClass('string', 'JsonSchema\Tests\Constraints\MyBadConstraint'); + $this->factory->setConstraintClass('string', 'JsonSchema\Tests\Constraints\MyBadConstraint'); } public function testSetConstraintClassInstance() { - $this->factory->setConstraintClass('string', 'JsonSchema\Tests\Constraints\MyStringConstraint'); - $constraint = $this->factory->createInstanceFor('string'); - $this->assertInstanceOf('JsonSchema\Tests\Constraints\MyStringConstraint', $constraint); - $this->assertInstanceOf('JsonSchema\Constraints\ConstraintInterface', $constraint); + $this->factory->setConstraintClass('string', 'JsonSchema\Tests\Constraints\MyStringConstraint'); + $constraint = $this->factory->createInstanceFor('string'); + $this->assertInstanceOf('JsonSchema\Tests\Constraints\MyStringConstraint', $constraint); + $this->assertInstanceOf('JsonSchema\Constraints\ConstraintInterface', $constraint); } public function testCheckMode() diff --git a/tests/Constraints/FormatTest.php b/tests/Constraints/FormatTest.php index d11d8c2c..a240b6df 100644 --- a/tests/Constraints/FormatTest.php +++ b/tests/Constraints/FormatTest.php @@ -21,7 +21,7 @@ public function setUp() public function testNullThing() { $validator = new FormatConstraint(); - $schema = new \stdClass; + $schema = new \stdClass(); $checkValue = 10; $validator->check($checkValue, $schema); @@ -31,7 +31,7 @@ public function testNullThing() public function testRegex() { $validator = new FormatConstraint(); - $schema = new \stdClass; + $schema = new \stdClass(); $schema->format = 'regex'; $validator->reset(); @@ -56,7 +56,7 @@ public function testRegex() public function testValidFormat($string, $format) { $validator = new FormatConstraint(); - $schema = new \stdClass; + $schema = new \stdClass(); $schema->format = $format; $validator->check($string, $schema); @@ -69,7 +69,7 @@ public function testValidFormat($string, $format) public function testInvalidFormat($string, $format) { $validator = new FormatConstraint(); - $schema = new \stdClass; + $schema = new \stdClass(); $schema->format = $format; $validator->check($string, $schema); @@ -154,7 +154,6 @@ public function getInvalidFormats() array('00:00:60', 'time'), array('25:00:00', 'time'), - array('invalid_value_2000-05-01T12:12:12Z', 'date-time'), array('2000-05-01T12:12:12Z_invalid_value', 'date-time'), array('1999-1-11T00:00:00Z', 'date-time'), @@ -183,7 +182,6 @@ public function getInvalidFormats() array('@localhost', 'host-name'), array('..nohost', 'host-name'), - ); } diff --git a/tests/Constraints/LongArraysTest.php b/tests/Constraints/LongArraysTest.php index 96c074f6..849c0371 100644 --- a/tests/Constraints/LongArraysTest.php +++ b/tests/Constraints/LongArraysTest.php @@ -30,7 +30,7 @@ public function testLongStringArray() $tmp = new \stdClass(); $tmp->p_array = array_map(function ($i) { - return "#".$i; + return '#' . $i; }, range(1, 100000)); $input = json_encode($tmp); @@ -102,6 +102,7 @@ public function testLongIntegerArray() private static function millis() { $mt = explode(' ', microtime()); + return $mt[1] * 1000 + round($mt[0] * 1000); } } diff --git a/tests/Constraints/MinLengthMaxLengthMultiByteTest.php b/tests/Constraints/MinLengthMaxLengthMultiByteTest.php index df00ce42..ab110a40 100644 --- a/tests/Constraints/MinLengthMaxLengthMultiByteTest.php +++ b/tests/Constraints/MinLengthMaxLengthMultiByteTest.php @@ -13,7 +13,7 @@ class MinLengthMaxLengthMultiByteTest extends BaseTestCase { protected function setUp() { - if (! extension_loaded('mbstring')) { + if (!extension_loaded('mbstring')) { $this->markTestSkipped('mbstring extension is not available'); } } diff --git a/tests/Constraints/MinLengthMaxLengthTest.php b/tests/Constraints/MinLengthMaxLengthTest.php index 8484c4e7..0e09a7a3 100644 --- a/tests/Constraints/MinLengthMaxLengthTest.php +++ b/tests/Constraints/MinLengthMaxLengthTest.php @@ -64,7 +64,6 @@ public function getValidTests() } }' ), - ); } } diff --git a/tests/Constraints/OfPropertiesTest.php b/tests/Constraints/OfPropertiesTest.php index 5255fc6e..c36ba29e 100644 --- a/tests/Constraints/OfPropertiesTest.php +++ b/tests/Constraints/OfPropertiesTest.php @@ -5,6 +5,7 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + namespace JsonSchema\Tests\Constraints; /** @@ -12,7 +13,6 @@ */ class OfPropertiesTest extends BaseTestCase { - public function getValidTests() { return array( @@ -72,22 +72,22 @@ public function getInvalidTests() null, array( array( - "property" => "prop2", - "pointer" => "/prop2", - "message" => "Array value found, but a string is required", - "constraint" => "type", + 'property' => 'prop2', + 'pointer' => '/prop2', + 'message' => 'Array value found, but a string is required', + 'constraint' => 'type', ), array( - "property" => "prop2", - "pointer" => "/prop2", - "message" => "Array value found, but a number is required", - "constraint" => "type", + 'property' => 'prop2', + 'pointer' => '/prop2', + 'message' => 'Array value found, but a number is required', + 'constraint' => 'type', ), array( - "property" => "prop2", - "pointer" => "/prop2", - "message" => "Failed to match exactly one schema", - "constraint" => "oneOf", + 'property' => 'prop2', + 'pointer' => '/prop2', + 'message' => 'Failed to match exactly one schema', + 'constraint' => 'oneOf', ), ), ), diff --git a/tests/Constraints/PatternPropertiesTest.php b/tests/Constraints/PatternPropertiesTest.php index 45108cd0..a04e45b9 100644 --- a/tests/Constraints/PatternPropertiesTest.php +++ b/tests/Constraints/PatternPropertiesTest.php @@ -49,7 +49,7 @@ public function getInvalidTests() 'type' => array('boolean') ) ), - "additionalProperties" => false + 'additionalProperties' => false )) ), // Does not match pattern with unicode @@ -64,7 +64,7 @@ public function getInvalidTests() 'type' => array('boolean') ) ), - "additionalProperties" => false + 'additionalProperties' => false )) ), // An invalid regular expression pattern @@ -79,7 +79,7 @@ public function getInvalidTests() 'type' => array('boolean') ) ), - "additionalProperties" => false + 'additionalProperties' => false )) ), ); @@ -189,7 +189,7 @@ public function getValidTests() 'type' => array('string', 'integer') ) ), - "additionalProperties" => false + 'additionalProperties' => false )) ), // Does match pattern with unicode @@ -204,10 +204,9 @@ public function getValidTests() 'type' => array('string') ) ), - "additionalProperties" => false + 'additionalProperties' => false )) ), ); } } - diff --git a/tests/Constraints/RequiredPropertyTest.php b/tests/Constraints/RequiredPropertyTest.php index 4938ec2e..10d42f57 100644 --- a/tests/Constraints/RequiredPropertyTest.php +++ b/tests/Constraints/RequiredPropertyTest.php @@ -14,7 +14,6 @@ class RequiredPropertyTest extends BaseTestCase { - public function testErrorPropertyIsPopulatedForRequiredIfMissingInInput() { $validator = new UndefinedConstraint(); @@ -36,7 +35,7 @@ public function testErrorPropertyIsPopulatedForRequiredIfMissingInInput() $validator->check($document, $schema); $error = $validator->getErrors(); - $this->assertErrorHasExpectedPropertyValue($error, "foo"); + $this->assertErrorHasExpectedPropertyValue($error, 'foo'); } public function testPathErrorPropertyIsPopulatedForRequiredIfMissingInInput() @@ -69,7 +68,7 @@ public function testPathErrorPropertyIsPopulatedForRequiredIfMissingInInput() $validator->check($document, $schema); $error = $validator->getErrors(); - $this->assertErrorHasExpectedPropertyValue($error, "foo[0].bar"); + $this->assertErrorHasExpectedPropertyValue($error, 'foo[0].bar'); } public function testErrorPropertyIsPopulatedForRequiredIfEmptyValueInInput() @@ -94,7 +93,7 @@ public function testErrorPropertyIsPopulatedForRequiredIfEmptyValueInInput() $validator->check($document, $schema); $error = $validator->getErrors(); - $this->assertErrorHasExpectedPropertyValue($error, "foo"); + $this->assertErrorHasExpectedPropertyValue($error, 'foo'); } protected function assertErrorHasExpectedPropertyValue($error, $propertyValue) @@ -102,11 +101,10 @@ protected function assertErrorHasExpectedPropertyValue($error, $propertyValue) if (!(isset($error[0]) && is_array($error[0]) && isset($error[0]['property']))) { $this->fail( "Malformed error response. Expected to have subset in form: array(0 => array('property' => )))" - . " . Error response was: " . json_encode($error) + . ' . Error response was: ' . json_encode($error) ); } $this->assertEquals($propertyValue, $error[0]['property']); - } public function getInvalidTests() diff --git a/tests/Constraints/SelfDefinedSchemaTest.php b/tests/Constraints/SelfDefinedSchemaTest.php index c49eef79..d2cce50e 100644 --- a/tests/Constraints/SelfDefinedSchemaTest.php +++ b/tests/Constraints/SelfDefinedSchemaTest.php @@ -9,7 +9,7 @@ namespace JsonSchema\Tests\Constraints; -use \JsonSchema\Validator; +use JsonSchema\Validator; class SelfDefinedSchemaTest extends BaseTestCase { diff --git a/tests/Constraints/TypeTest.php b/tests/Constraints/TypeTest.php index fdc3f907..10d3ad21 100644 --- a/tests/Constraints/TypeTest.php +++ b/tests/Constraints/TypeTest.php @@ -15,27 +15,29 @@ * Class TypeTest * * @package JsonSchema\Tests\Constraints + * * @author hakre */ class TypeTest extends \PHPUnit_Framework_TestCase { /** * @see testIndefiniteArticleForTypeInTypeCheckErrorMessage + * * @return array */ public function provideIndefiniteArticlesForTypes() { return array( - array('integer', 'an integer',), - array('number', 'a number',), - array('boolean', 'a boolean',), - array('object', 'an object',), - array('array', 'an array',), - array('string', 'a string',), - array('null', 'a null', array(), 'array',), - array(array('string', 'boolean', 'integer'), 'a string, a boolean or an integer',), - array(array('string', 'boolean'), 'a string or a boolean',), - array(array('string'), 'a string',), + array('integer', 'an integer'), + array('number', 'a number'), + array('boolean', 'a boolean'), + array('object', 'an object'), + array('array', 'an array'), + array('string', 'a string'), + array('null', 'a null', array(), 'array'), + array(array('string', 'boolean', 'integer'), 'a string, a boolean or an integer'), + array(array('string', 'boolean'), 'a string or a boolean'), + array(array('string'), 'a string'), ); } @@ -45,21 +47,21 @@ public function provideIndefiniteArticlesForTypes() public function testIndefiniteArticleForTypeInTypeCheckErrorMessage($type, $wording, $value = null, $label = 'NULL') { $constraint = new TypeConstraint(); - $constraint->check($value, (object)array('type' => $type)); - $this->assertTypeConstraintError(ucwords($label)." value found, but $wording is required", $constraint); + $constraint->check($value, (object) array('type' => $type)); + $this->assertTypeConstraintError(ucwords($label) . " value found, but $wording is required", $constraint); } /** * Helper to assert an error message * - * @param string $expected + * @param string $expected * @param TypeConstraint $actual */ private function assertTypeConstraintError($expected, TypeConstraint $actual) { $actualErrors = $actual->getErrors(); - $this->assertCount(1, $actualErrors, "Failed to assert that Type has exactly one error to assert the error message against."); + $this->assertCount(1, $actualErrors, 'Failed to assert that Type has exactly one error to assert the error message against.'); $actualError = $actualErrors[0]; diff --git a/tests/Constraints/ValidationExceptionTest.php b/tests/Constraints/ValidationExceptionTest.php index 8fcbbcef..6a7076bb 100644 --- a/tests/Constraints/ValidationExceptionTest.php +++ b/tests/Constraints/ValidationExceptionTest.php @@ -9,9 +9,9 @@ namespace JsonSchema\Tests\Constraints; -use JsonSchema\Validator; use JsonSchema\Constraints\Constraint; use JsonSchema\Exception\ValidationException; +use JsonSchema\Validator; class ValidationExceptionTest extends \PHPUnit_Framework_TestCase { @@ -44,9 +44,7 @@ public function testValidationException() $exception->getMessage() ); - $this->setExpectedException('JsonSchema\Exception\ValidationException'); throw $exception; - } } diff --git a/tests/Constraints/VeryBaseTestCase.php b/tests/Constraints/VeryBaseTestCase.php index 90063718..7d8eb267 100644 --- a/tests/Constraints/VeryBaseTestCase.php +++ b/tests/Constraints/VeryBaseTestCase.php @@ -24,6 +24,7 @@ abstract class VeryBaseTestCase extends \PHPUnit_Framework_TestCase /** * @param object $schema + * * @return object */ protected function getUriRetrieverMock($schema) @@ -46,12 +47,15 @@ protected function getUriRetrieverMock($schema) return $jsonSchemaDraft04; } elseif (0 === strpos($args[0], 'http://localhost:1234')) { $urlParts = parse_url($args[0]); + return json_decode(file_get_contents($relativeTestsRoot . $urlParts['path'])); } elseif (0 === strpos($args[0], 'http://www.my-domain.com')) { $urlParts = parse_url($args[0]); + return json_decode(file_get_contents($relativeTestsRoot . '/folder' . $urlParts['path'])); } }); + return $uriRetriever->reveal(); } diff --git a/tests/Drafts/BaseDraftTestCase.php b/tests/Drafts/BaseDraftTestCase.php index 6e9e06f0..1cfe634c 100644 --- a/tests/Drafts/BaseDraftTestCase.php +++ b/tests/Drafts/BaseDraftTestCase.php @@ -9,7 +9,7 @@ */ abstract class BaseDraftTestCase extends BaseTestCase { - /** @var string */ + /** @var string */ protected $relativeTestsRoot = '/../../vendor/json-schema/JSON-Schema-Test-Suite/tests'; private function setUpTests($isValid) @@ -62,12 +62,12 @@ public function getValidTests() /** * @return string[] */ - protected abstract function getFilePaths(); + abstract protected function getFilePaths(); /** * @return string[] */ - protected abstract function getSkippedTests(); + abstract protected function getSkippedTests(); /** * Generates a readable path to Json Schema Test Suite data set under test @@ -81,6 +81,7 @@ protected abstract function getSkippedTests(); private function createDataSetPath($filename, $suiteDesc, $testCaseDesc) { $separator = ' / '; + return $filename . $separator . $suiteDesc . $separator . $testCaseDesc; } } diff --git a/tests/Drafts/Draft3Test.php b/tests/Drafts/Draft3Test.php index 72ec0ebd..4a744441 100644 --- a/tests/Drafts/Draft3Test.php +++ b/tests/Drafts/Draft3Test.php @@ -8,6 +8,7 @@ */ namespace JsonSchema\Tests\Drafts; + use JsonSchema\Constraints\Constraint; /** diff --git a/tests/Entity/JsonPointerTest.php b/tests/Entity/JsonPointerTest.php index 1cc8c0bf..6a5ff4bf 100644 --- a/tests/Entity/JsonPointerTest.php +++ b/tests/Entity/JsonPointerTest.php @@ -13,6 +13,7 @@ /** * @package JsonSchema\Tests\Entity + * * @author Joost Nijhuis */ class JsonPointerTest extends \PHPUnit_Framework_TestCase @@ -22,7 +23,7 @@ class JsonPointerTest extends \PHPUnit_Framework_TestCase * * @param string $testValue * @param string $expectedFileName - * @param array $expectedPropertyPaths + * @param array $expectedPropertyPaths * @param string $expectedPropertyPathAsString * @param string $expectedToString */ @@ -88,8 +89,6 @@ public function getTestData() 'expectedPropertyPathAsString' => '#/items/0', 'expectedToString' => '#/items/0' ) - - ); } diff --git a/tests/Exception/JsonDecodingExceptionTest.php b/tests/Exception/JsonDecodingExceptionTest.php index 6a0cb581..bd9ccb6f 100644 --- a/tests/Exception/JsonDecodingExceptionTest.php +++ b/tests/Exception/JsonDecodingExceptionTest.php @@ -13,59 +13,59 @@ public function testHierarchy() self::assertInstanceOf('\JsonSchema\Exception\RuntimeException', $exception); self::assertInstanceOf('\JsonSchema\Exception\ExceptionInterface', $exception); } - + public function testDefaultMessage() { $exception = new JsonDecodingException(); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorNoneMessage() { $exception = new JsonDecodingException(JSON_ERROR_NONE); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorDepthMessage() { $exception = new JsonDecodingException(JSON_ERROR_DEPTH); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorStateMismatchMessage() { $exception = new JsonDecodingException(JSON_ERROR_STATE_MISMATCH); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorControlCharacterMessage() { $exception = new JsonDecodingException(JSON_ERROR_CTRL_CHAR); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorUtf8Message() { $exception = new JsonDecodingException(JSON_ERROR_UTF8); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorSyntaxMessage() { $exception = new JsonDecodingException(JSON_ERROR_SYNTAX); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorInfiniteOrNotANumberMessage() { if (!defined('JSON_ERROR_INF_OR_NAN')) { self::markTestSkipped('JSON_ERROR_INF_OR_NAN is not defined until php55.'); } - + $exception = new JsonDecodingException(JSON_ERROR_INF_OR_NAN); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorRecursionMessage() { if (!defined('JSON_ERROR_RECURSION')) { @@ -75,7 +75,7 @@ public function testErrorRecursionMessage() $exception = new JsonDecodingException(JSON_ERROR_RECURSION); self::assertNotEmpty($exception->getMessage()); } - + public function testErrorUnsupportedTypeMessage() { if (!defined('JSON_ERROR_UNSUPPORTED_TYPE')) { diff --git a/tests/Rfc3339Test.php b/tests/Rfc3339Test.php index 3169e983..d01da520 100644 --- a/tests/Rfc3339Test.php +++ b/tests/Rfc3339Test.php @@ -7,7 +7,7 @@ class Rfc3339Test extends \PHPUnit_Framework_TestCase { /** - * @param string $string + * @param string $string * @param \DateTime|null $expected * @dataProvider provideValidFormats */ diff --git a/tests/SchemaStorageTest.php b/tests/SchemaStorageTest.php index 221ec668..c3388bf4 100644 --- a/tests/SchemaStorageTest.php +++ b/tests/SchemaStorageTest.php @@ -136,7 +136,7 @@ private function getMainSchema() 'additionalProperties' => false, 'properties' => (object) array( '$ref' => '#/definitions/yardproperties' - ) + ) ) ), 'definitions' => (object) array( diff --git a/tests/Uri/Retrievers/FileGetContentsTest.php b/tests/Uri/Retrievers/FileGetContentsTest.php index 9c37a1cf..7b67facb 100644 --- a/tests/Uri/Retrievers/FileGetContentsTest.php +++ b/tests/Uri/Retrievers/FileGetContentsTest.php @@ -10,12 +10,12 @@ class FileGetContentsTest extends \PHPUnit_Framework_TestCase { /** - * @expectedException JsonSchema\Exception\ResourceNotFoundException + * @expectedException \JsonSchema\Exception\ResourceNotFoundException */ public function testFetchMissingFile() { $res = new FileGetContents(); - $res->retrieve(__DIR__.'/Fixture/missing.json'); + $res->retrieve(__DIR__ . '/Fixture/missing.json'); } public function testFetchFile() diff --git a/tests/Uri/Retrievers/PredefinedArrayTest.php b/tests/Uri/Retrievers/PredefinedArrayTest.php index d01b835d..e92908a2 100644 --- a/tests/Uri/Retrievers/PredefinedArrayTest.php +++ b/tests/Uri/Retrievers/PredefinedArrayTest.php @@ -29,7 +29,7 @@ public function testRetrieve() } /** - * @expectedException JsonSchema\Exception\ResourceNotFoundException + * @expectedException \JsonSchema\Exception\ResourceNotFoundException */ public function testRetrieveNonExistsingSchema() { diff --git a/tests/Uri/UriResolverTest.php b/tests/Uri/UriResolverTest.php index 872972fd..ea564f65 100644 --- a/tests/Uri/UriResolverTest.php +++ b/tests/Uri/UriResolverTest.php @@ -1,4 +1,5 @@ assertEquals( @@ -171,4 +173,3 @@ public function testResolveEmpty() ); } } -?> diff --git a/tests/Uri/UriRetrieverTest.php b/tests/Uri/UriRetrieverTest.php index 11f21bd5..5d0d0e95 100644 --- a/tests/Uri/UriRetrieverTest.php +++ b/tests/Uri/UriRetrieverTest.php @@ -139,6 +139,7 @@ public function jsonProvider() } } EOF; + return array( array($childSchema, $parentSchema) ); @@ -180,7 +181,7 @@ public function testResolvePointerFragment() } /** - * @expectedException JsonSchema\Exception\ResourceNotFoundException + * @expectedException \JsonSchema\Exception\ResourceNotFoundException */ public function testResolvePointerFragmentNotFound() { @@ -200,7 +201,7 @@ public function testResolvePointerFragmentNotFound() } /** - * @expectedException JsonSchema\Exception\ResourceNotFoundException + * @expectedException \JsonSchema\Exception\ResourceNotFoundException */ public function testResolvePointerFragmentNoArray() { @@ -220,7 +221,7 @@ public function testResolvePointerFragmentNoArray() } /** - * @expectedException JsonSchema\Exception\UriResolverException + * @expectedException \JsonSchema\Exception\UriResolverException */ public function testResolveExcessLevelUp() { @@ -232,24 +233,24 @@ public function testResolveExcessLevelUp() public function testConfirmMediaTypeAcceptsJsonSchemaType() { - $retriever = $this->getMock('JsonSchema\Uri\UriRetriever', array('getContentType')); + $retriever = $this->getMock('JsonSchema\Uri\UriRetriever', array('getContentType')); - $retriever->expects($this->at(0)) + $retriever->expects($this->at(0)) ->method('getContentType') ->will($this->returnValue('application/schema+json')); - $this->assertEquals(null, $retriever->confirmMediaType($retriever, null)); + $this->assertEquals(null, $retriever->confirmMediaType($retriever, null)); } public function testConfirmMediaTypeAcceptsJsonType() { - $retriever = $this->getMock('JsonSchema\Uri\UriRetriever', array('getContentType')); + $retriever = $this->getMock('JsonSchema\Uri\UriRetriever', array('getContentType')); - $retriever->expects($this->at(0)) + $retriever->expects($this->at(0)) ->method('getContentType') ->will($this->returnValue('application/json')); - $this->assertEquals(null, $retriever->confirmMediaType($retriever, null)); + $this->assertEquals(null, $retriever->confirmMediaType($retriever, null)); } /** @@ -257,13 +258,13 @@ public function testConfirmMediaTypeAcceptsJsonType() */ public function testConfirmMediaTypeThrowsExceptionForUnsupportedTypes() { - $retriever = $this->getMock('JsonSchema\Uri\UriRetriever', array('getContentType')); + $retriever = $this->getMock('JsonSchema\Uri\UriRetriever', array('getContentType')); - $retriever->expects($this->at(0)) + $retriever->expects($this->at(0)) ->method('getContentType') ->will($this->returnValue('text/html')); - $this->assertEquals(null, $retriever->confirmMediaType($retriever, null)); + $this->assertEquals(null, $retriever->confirmMediaType($retriever, null)); } private function mockRetriever($schema)