diff --git a/.travis.yml b/.travis.yml index a411dd4..6265f4f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,23 +12,22 @@ cache: matrix: include: - - php: 5.3 - - php: 5.4 - - php: 5.5 - - php: 5.6 - - php: hhvm - - php: nightly - - php: 7.0 + - php: 7.3 env: COVERAGE=yes - - php: 7.0 + - php: 7.3 + env: COMPOSER_FLAGS='--prefer-lowest --prefer-stable' + - php: 7.4 + env: COVERAGE=yes + - php: 7.4 + env: COMPOSER_FLAGS='--prefer-lowest --prefer-stable' + - php: 8.0 + env: COVERAGE=yes + - php: 8.0 env: COMPOSER_FLAGS='--prefer-lowest --prefer-stable' - allow_failures: - - php: hhvm - - php: nightly fast_finish: true before_install: - - if [[ $TRAVIS_PHP_VERSION != hhvm && $COVERAGE != yes ]]; then phpenv config-rm xdebug.ini; fi; + - if [[ $COVERAGE != yes ]]; then phpenv config-rm xdebug.ini; fi; - if [[ $TRAVIS_REPO_SLUG = webmozart/json ]]; then cp .composer-auth.json ~/.composer/auth.json; fi; - composer self-update diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e26200..07ec327 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,15 @@ Changelog ========= +* 2.0.0 (@release_date@) + + * dropped support for PHP ^5.2 + * dropped support for PHP 7.0 + * dropped support for PHP 7.1 + * dropped support for PHP 7.2 + * upgraded dependencies + * added PHP 8 compatibility + * 1.3.0 (@release_date@) * added `JsonConverter` and `ConversionException` diff --git a/README.md b/README.md index 04034c3..38f7617 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ Webmozart JSON [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/webmozart/json/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/webmozart/json/?branch=master) [![Latest Stable Version](https://poser.pugx.org/webmozart/json/v/stable.svg)](https://packagist.org/packages/webmozart/json) [![Total Downloads](https://poser.pugx.org/webmozart/json/downloads.svg)](https://packagist.org/packages/webmozart/json) -[![Dependency Status](https://www.versioneye.com/php/webmozart:json/1.2.2/badge.svg)](https://www.versioneye.com/php/webmozart:json/1.2.2) +[![Dependency Status](https://www.versioneye.com/php/webmozart:json/2.0.0/badge.svg)](https://www.versioneye.com/php/webmozart:json/2.0.0) -Latest release: [1.2.2](https://packagist.org/packages/webmozart/json#1.2.2) +Latest release: [2.0.0](https://packagist.org/packages/webmozart/json#2.0.0) A robust wrapper for `json_encode()`/`json_decode()` that normalizes their behavior across PHP versions, throws meaningful exceptions and supports schema diff --git a/composer.json b/composer.json index f7b3624..50c0e12 100644 --- a/composer.json +++ b/composer.json @@ -9,16 +9,17 @@ } ], "require": { - "php": "^5.3.3|^7.0", - "justinrainbow/json-schema": "^2.0", - "seld/jsonlint": "^1.0", - "webmozart/assert": "^1.0", - "webmozart/path-util": "^2.3" + "php": ">=7.3", + "justinrainbow/json-schema": "^5.2", + "seld/jsonlint": "^1.8", + "webmozart/assert": "^1.9", + "webmozart/path-util": "^2.3", + "ext-json": "*" }, "require-dev": { - "phpunit/phpunit": "^4.6", - "sebastian/version": "^1.0.1", - "symfony/filesystem": "^2.5" + "phpunit/phpunit": "^9.5", + "sebastian/version": "^3.0.2", + "symfony/filesystem": "^5.2" }, "autoload": { "psr-4": { diff --git a/src/InvalidSchemaException.php b/src/InvalidSchemaException.php deleted file mode 100644 index 89b5545..0000000 --- a/src/InvalidSchemaException.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Webmozart\Json; - -use RuntimeException; - -/** - * Thrown a JSON schema cannot be loaded. - * - * @since 1.0 - * - * @author Bernhard Schussek - */ -class InvalidSchemaException extends RuntimeException -{ -} diff --git a/src/JsonDecoder.php b/src/JsonDecoder.php index c5a75f8..7476695 100644 --- a/src/JsonDecoder.php +++ b/src/JsonDecoder.php @@ -11,6 +11,7 @@ namespace Webmozart\Json; +use JsonSchema\Validator; use Seld\JsonLint\JsonParser; use Seld\JsonLint\ParsingException; @@ -44,7 +45,7 @@ class JsonDecoder const STRING = 3; /** - * @var JsonValidator + * @var Validator */ private $validator; @@ -66,11 +67,11 @@ class JsonDecoder /** * Creates a new decoder. * - * @param null|JsonValidator $validator + * @param null|Validator $validator */ - public function __construct(JsonValidator $validator = null) + public function __construct(Validator $validator = null) { - $this->validator = $validator ?: new JsonValidator(); + $this->validator = $validator ?? new Validator(); } /** @@ -94,7 +95,6 @@ public function __construct(JsonValidator $validator = null) * @throws DecodingFailedException If the JSON string could not be decoded * @throws ValidationFailedException If the decoded string fails schema * validation - * @throws InvalidSchemaException If the schema is invalid */ public function decode($json, $schema = null) { @@ -109,7 +109,8 @@ public function decode($json, $schema = null) $decoded = $this->decodeJson($json); if (null !== $schema) { - $errors = $this->validator->validate($decoded, $schema); + $this->validator->validate($decoded, $schema); + $errors = $this->validator->getErrors(); if (count($errors) > 0) { throw ValidationFailedException::fromErrors($errors); @@ -131,7 +132,6 @@ public function decode($json, $schema = null) * @throws DecodingFailedException If the file could not be decoded * @throws ValidationFailedException If the decoded file fails schema * validation - * @throws InvalidSchemaException If the schema is invalid * * @see decode */ @@ -170,6 +170,10 @@ public function decodeFile($path, $schema = null) ), $errorCode); } + if (false === $content) { + throw new IOException(sprintf('Could not read %s', $path)); + } + try { return $this->decode($content, $schema); } catch (DecodingFailedException $e) { @@ -186,13 +190,6 @@ public function decodeFile($path, $schema = null) $path, $e->getErrorsAsString() ), $e->getErrors(), $e->getCode(), $e); - } catch (InvalidSchemaException $e) { - // Add the file name to the exception - throw new InvalidSchemaException(sprintf( - 'An error happened while decoding %s: %s', - $path, - $e->getMessage() - ), $e->getCode(), $e); } } diff --git a/src/JsonEncoder.php b/src/JsonEncoder.php index fc7b30a..3d9e586 100644 --- a/src/JsonEncoder.php +++ b/src/JsonEncoder.php @@ -11,6 +11,8 @@ namespace Webmozart\Json; +use JsonSchema\Validator; + /** * Encodes data as JSON. * @@ -41,7 +43,7 @@ class JsonEncoder const JSON_NUMBER = 4; /** - * @var JsonValidator + * @var Validator */ private $validator; @@ -103,11 +105,11 @@ class JsonEncoder /** * Creates a new encoder. * - * @param null|JsonValidator $validator + * @param null|Validator $validator */ - public function __construct(JsonValidator $validator = null) + public function __construct(Validator $validator = null) { - $this->validator = $validator ?: new JsonValidator(); + $this->validator = $validator ?? new Validator(); } /** @@ -126,12 +128,12 @@ public function __construct(JsonValidator $validator = null) * * @throws EncodingFailedException If the data could not be encoded * @throws ValidationFailedException If the data fails schema validation - * @throws InvalidSchemaException If the schema is invalid */ public function encode($data, $schema = null) { if (null !== $schema) { - $errors = $this->validator->validate($data, $schema); + $this->validator->validate($data, $schema); + $errors = $this->validator->getErrors(); if (count($errors) > 0) { throw ValidationFailedException::fromErrors($errors); @@ -178,21 +180,6 @@ public function encode($data, $schema = null) } } - if (PHP_VERSION_ID < 71000) { - // PHP before 7.1 decodes empty properties as "_empty_". Make - // sure the encoding of these properties works again. - if (is_object($data) && isset($data->{'_empty_'})) { - $data = (array) $data; - } - - if (is_array($data) && isset($data['_empty_'])) { - // Maintain key order - $keys = array_keys($data); - $keys[array_search('_empty_', $keys, true)] = ''; - $data = array_combine($keys, $data); - } - } - if (PHP_VERSION_ID >= 50500) { $maxDepth = $this->maxDepth; @@ -210,12 +197,6 @@ public function encode($data, $schema = null) $encoded = json_encode($data, $options); } - if (PHP_VERSION_ID < 50400 && !$this->slashEscaped) { - // PHP below 5.4 does not allow to turn off slash escaping. Let's - // unescape slashes manually. - $encoded = str_replace('\\/', '/', $encoded); - } - if (JSON_ERROR_NONE !== json_last_error()) { throw new EncodingFailedException(sprintf( 'The data could not be encoded as JSON: %s', @@ -239,7 +220,6 @@ public function encode($data, $schema = null) * * @throws EncodingFailedException If the data could not be encoded * @throws ValidationFailedException If the data fails schema validation - * @throws InvalidSchemaException If the schema is invalid * * @see encode */ @@ -268,13 +248,6 @@ public function encodeFile($data, $path, $schema = null) $path, $e->getErrorsAsString() ), $e->getErrors(), $e->getCode(), $e); - } catch (InvalidSchemaException $e) { - // Add the file name to the exception - throw new InvalidSchemaException(sprintf( - 'An error happened while encoding %s: %s', - $path, - $e->getMessage() - ), $e->getCode(), $e); } $errorMessage = null; diff --git a/src/JsonValidator.php b/src/JsonValidator.php deleted file mode 100644 index e1cb82d..0000000 --- a/src/JsonValidator.php +++ /dev/null @@ -1,185 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Webmozart\Json; - -use JsonSchema\Exception\InvalidArgumentException; -use JsonSchema\Exception\ResourceNotFoundException; -use JsonSchema\RefResolver; -use JsonSchema\Uri\UriResolver; -use JsonSchema\Uri\UriRetriever; -use JsonSchema\UriResolverInterface; -use JsonSchema\Validator; -use Webmozart\PathUtil\Path; - -/** - * Validates decoded JSON values against a JSON schema. - * - * This class is a wrapper for {@link Validator} that adds exceptions and - * validation of schema files. A few edge cases that are not handled by - * {@link Validator} are handled by this class. - * - * @since 1.0 - * - * @author Bernhard Schussek - */ -class JsonValidator -{ - /** - * The schema used for validating schemas. - * - * @var object|null - */ - private $metaSchema; - - /** - * Validator instance used for validation. - * - * @var Validator - */ - private $validator; - - /** - * Reference resolver. - * - * @var RefResolver - */ - private $resolver; - - /** - * JsonValidator constructor. - * - * @param Validator|null $validator JsonSchema\Validator - * instance to use - * @param UriRetriever|null $uriRetriever The retriever for fetching - * JSON schemas - * @param UriResolverInterface|null $uriResolver The resolver for URIs - */ - public function __construct(Validator $validator = null, UriRetriever $uriRetriever = null, UriResolverInterface $uriResolver = null) - { - $this->validator = $validator ?: new Validator(); - $this->resolver = new RefResolver($uriRetriever ?: new UriRetriever(), $uriResolver ?: new UriResolver()); - } - - /** - * Validates JSON data against a schema. - * - * The schema may be passed as file path or as object returned from - * `json_decode($schemaFile)`. - * - * @param mixed $data The decoded JSON data - * @param string|object|null $schema The schema file or object. If `null`, - * the validator will look for a `$schema` - * property - * - * @return string[] The errors found during validation. Returns an empty - * array if no errors were found - * - * @throws InvalidSchemaException If the schema is invalid - */ - public function validate($data, $schema = null) - { - if (null === $schema && isset($data->{'$schema'})) { - $schema = $data->{'$schema'}; - } - - if (is_string($schema)) { - $schema = $this->loadSchema($schema); - } elseif (is_object($schema)) { - $this->assertSchemaValid($schema); - } else { - throw new InvalidSchemaException(sprintf( - 'The schema must be given as string, object or in the "$schema" '. - 'property of the JSON data. Got: %s', - is_object($schema) ? get_class($schema) : gettype($schema) - )); - } - - $this->validator->reset(); - - try { - $this->validator->check($data, $schema); - } catch (InvalidArgumentException $e) { - throw new InvalidSchemaException(sprintf( - 'The schema is invalid: %s', - $e->getMessage() - ), 0, $e); - } - - $errors = array(); - - if (!$this->validator->isValid()) { - $errors = (array) $this->validator->getErrors(); - - foreach ($errors as $key => $error) { - $prefix = $error['property'] ? $error['property'].': ' : ''; - $errors[$key] = $prefix.$error['message']; - } - } - - return $errors; - } - - private function assertSchemaValid($schema) - { - if (null === $this->metaSchema) { - // The meta schema is obviously not validated. If we - // validate it against itself, we have an endless recursion - $this->metaSchema = json_decode(file_get_contents(__DIR__.'/../res/meta-schema.json')); - } - - if ($schema === $this->metaSchema) { - return; - } - - $errors = $this->validate($schema, $this->metaSchema); - - if (count($errors) > 0) { - throw new InvalidSchemaException(sprintf( - "The schema is invalid:\n%s", - implode("\n", $errors) - )); - } - } - - private function loadSchema($file) - { - // Retrieve schema and cache in UriRetriever - $file = Path::canonicalize($file); - - // Add file:// scheme if necessary - if (false === strpos($file, '://')) { - $file = 'file://'.$file; - } - - // Resolve references to other schemas - try { - $schema = $this->resolver->resolve($file); - } catch (ResourceNotFoundException $e) { - throw new InvalidSchemaException(sprintf( - 'The schema %s does not exist.', - $file - ), 0, $e); - } - - try { - $this->assertSchemaValid($schema); - } catch (InvalidSchemaException $e) { - throw new InvalidSchemaException(sprintf( - 'An error occurred while loading the schema %s: %s', - $file, - $e->getMessage() - ), 0, $e); - } - - return $schema; - } -} diff --git a/src/Validation/ValidatingConverter.php b/src/Validation/ValidatingConverter.php index 60a7bcb..7a6da3f 100644 --- a/src/Validation/ValidatingConverter.php +++ b/src/Validation/ValidatingConverter.php @@ -11,10 +11,9 @@ namespace Webmozart\Json\Validation; +use JsonSchema\Validator; use Webmozart\Json\Conversion\ConversionFailedException; use Webmozart\Json\Conversion\JsonConverter; -use Webmozart\Json\InvalidSchemaException; -use Webmozart\Json\JsonValidator; /** * A decorator for a {@link JsonCoverter} that validates the JSON data. @@ -72,9 +71,9 @@ class ValidatingConverter implements JsonConverter private $schema; /** - * @var JsonValidator + * @var Validator */ - private $jsonValidator; + private $validator; /** * Creates the converter. @@ -87,13 +86,13 @@ class ValidatingConverter implements JsonConverter * the schema is taken from the * `$schema` property of the * JSON data - * @param JsonValidator $jsonValidator The JSON validator (optional) + * @param null|Validator $validator The validator (optional) */ - public function __construct(JsonConverter $innerConverter, $schema = null, JsonValidator $jsonValidator = null) + public function __construct(JsonConverter $innerConverter, $schema = null, Validator $validator = null) { $this->innerConverter = $innerConverter; $this->schema = $schema; - $this->jsonValidator = $jsonValidator ?: new JsonValidator(); + $this->validator = $validator ?? new Validator(); } /** @@ -126,17 +125,24 @@ private function validate($jsonData) $schema = $schema($jsonData); } - try { - $errors = $this->jsonValidator->validate($jsonData, $schema); - } catch (InvalidSchemaException $e) { - throw new ConversionFailedException(sprintf( - 'An error occurred while loading the JSON schema (%s): %s', - is_string($schema) ? '"'.$schema.'"' : gettype($schema), - $e->getMessage() - ), 0, $e); + $this->validator->validate($jsonData, $schema); + + $errors = $this->validator->getErrors(); + + if (null === $errors) { + return; } if (count($errors) > 0) { + foreach ($errors as &$error) { + if (!is_array($error)) { + continue; + } + + $error = implode("\n", $error); + } + unset($error); + throw new ConversionFailedException(sprintf( "The passed JSON did not match the schema:\n%s", implode("\n", $errors) diff --git a/src/ValidationFailedException.php b/src/ValidationFailedException.php index 7414b41..95ccdec 100644 --- a/src/ValidationFailedException.php +++ b/src/ValidationFailedException.php @@ -24,6 +24,15 @@ class ValidationFailedException extends \Exception public static function fromErrors(array $errors = array(), $code = 0, \Exception $previous = null) { + foreach ($errors as &$error) { + if (!is_array($error)) { + continue; + } + + $error = implode("\n", $error); + } + unset($error); + return new static(sprintf( "Validation of the JSON data failed:\n%s", implode("\n", $errors) diff --git a/tests/JsonDecoderTest.php b/tests/JsonDecoderTest.php index c036355..632a647 100644 --- a/tests/JsonDecoderTest.php +++ b/tests/JsonDecoderTest.php @@ -11,14 +11,21 @@ namespace Webmozart\Json\Tests; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; +use stdClass; +use Webmozart\Json\DecodingFailedException; +use Webmozart\Json\FileNotFoundException; +use Webmozart\Json\IOException; use Webmozart\Json\JsonDecoder; +use Webmozart\Json\ValidationFailedException; /** * @since 1.0 * * @author Bernhard Schussek */ -class JsonDecoderTest extends \PHPUnit_Framework_TestCase +class JsonDecoderTest extends TestCase { /** * @var JsonDecoder @@ -31,7 +38,7 @@ class JsonDecoderTest extends \PHPUnit_Framework_TestCase private $schemaObject; - protected function setUp() + protected function setUp(): void { $this->decoder = new JsonDecoder(); $this->fixturesDir = __DIR__.'/Fixtures'; @@ -39,164 +46,130 @@ protected function setUp() $this->schemaObject = json_decode(file_get_contents($this->schemaFile)); } - public function testDecode() + public function testDecode(): void { $data = $this->decoder->decode('{ "name": "Bernhard" }'); - $this->assertInstanceOf('\stdClass', $data); - $this->assertObjectHasAttribute('name', $data); - $this->assertSame('Bernhard', $data->name); + self::assertInstanceOf(stdClass::class, $data); + self::assertObjectHasAttribute('name', $data); + self::assertSame('Bernhard', $data->name); } - public function testDecodeEmptyObject() + public function testDecodeEmptyObject(): void { $data = $this->decoder->decode('{}'); - $this->assertEquals((object) array(), $data); - $this->assertInstanceOf('\stdClass', $data); + self::assertEquals((object) array(), $data); + self::assertInstanceOf(stdClass::class, $data); } - public function testDecodeNull() + public function testDecodeNull(): void { $data = $this->decoder->decode('null'); - $this->assertNull($data); + self::assertNull($data); } - public function testDecodeNestedEmptyObject() + public function testDecodeNestedEmptyObject(): void { $data = $this->decoder->decode('{ "empty": {} }'); - $this->assertEquals((object) array('empty' => (object) array()), $data); - $this->assertInstanceOf('\stdClass', $data); - $this->assertInstanceOf('\stdClass', $data->empty); + self::assertEquals((object) array('empty' => (object) array()), $data); + self::assertInstanceOf(stdClass::class, $data); + self::assertInstanceOf(stdClass::class, $data->empty); } - public function testDecodeWithSchemaFile() + public function testDecodeWithSchemaFile(): void { $data = $this->decoder->decode('{ "name": "Bernhard" }', $this->schemaFile); - $this->assertInstanceOf('\stdClass', $data); - $this->assertObjectHasAttribute('name', $data); - $this->assertSame('Bernhard', $data->name); + self::assertInstanceOf(stdClass::class, $data); + self::assertObjectHasAttribute('name', $data); + self::assertSame('Bernhard', $data->name); } - public function testDecodeWithSchemaObject() + public function testDecodeWithSchemaObject(): void { $data = $this->decoder->decode('{ "name": "Bernhard" }', $this->schemaObject); - $this->assertInstanceOf('\stdClass', $data); - $this->assertObjectHasAttribute('name', $data); - $this->assertSame('Bernhard', $data->name); + self::assertInstanceOf(stdClass::class, $data); + self::assertObjectHasAttribute('name', $data); + self::assertSame('Bernhard', $data->name); } - /** - * @expectedException \Webmozart\Json\ValidationFailedException - */ - public function testDecodeFailsIfValidationFailsWithSchemaFile() + public function testDecodeFailsIfValidationFailsWithSchemaObject(): void { - $this->decoder->decode('"foobar"', $this->schemaFile); - } + $this->expectException(ValidationFailedException::class); - /** - * @expectedException \Webmozart\Json\ValidationFailedException - */ - public function testDecodeFailsIfValidationFailsWithSchemaObject() - { $this->decoder->decode('"foobar"', $this->schemaObject); } - public function testDecodeUtf8() + public function testDecodeUtf8(): void { $data = $this->decoder->decode('{"name":"B\u00e9rnhard"}'); - $this->assertEquals((object) array('name' => 'Bérnhard'), $data); + self::assertEquals((object) array('name' => 'Bérnhard'), $data); } /** * JSON_ERROR_UTF8. - * - * @expectedException \Webmozart\Json\DecodingFailedException - * @expectedExceptionCode 5 */ - public function testDecodeFailsIfNotUtf8() + public function testDecodeFailsIfNotUtf8(): void { if (defined('JSON_C_VERSION')) { - $this->markTestSkipped('This error is not reported when using JSONC.'); + self::markTestSkipped('This error is not reported when using JSONC.'); } + $this->expectException(DecodingFailedException::class); + $this->expectExceptionCode(5); + $win1258 = file_get_contents($this->fixturesDir.'/win-1258.json'); $this->decoder->decode($win1258); } - public function testDecodeObjectAsObject() + public function testDecodeObjectAsObject(): void { $this->decoder->setObjectDecoding(JsonDecoder::OBJECT); $decoded = $this->decoder->decode('{ "name": "Bernhard" }'); - $this->assertEquals((object) array('name' => 'Bernhard'), $decoded); + self::assertEquals((object) array('name' => 'Bernhard'), $decoded); } - public function testDecodeObjectAsArray() + public function testDecodeObjectAsArray(): void { $this->decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY); $decoded = $this->decoder->decode('{ "name": "Bernhard" }'); - $this->assertEquals(array('name' => 'Bernhard'), $decoded); + self::assertEquals(array('name' => 'Bernhard'), $decoded); } - public function testDecodeEmptyArrayKey() + public function testDecodeEmptyArrayKey(): void { $data = array('' => 'Bernhard'); $this->decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY); - $this->assertEquals($data, $this->decoder->decode('{"":"Bernhard"}')); + self::assertEquals($data, $this->decoder->decode('{"":"Bernhard"}')); } - public function testDecodeEmptyProperty() + public function testDecodeEmptyProperty(): void { - if (version_compare(PHP_VERSION, '7.1.0', '<')) { - $this->markTestSkipped('PHP >= 7.1.0 only'); - - return; - } - $data = (object) array('' => 'Bernhard'); - $this->assertEquals($data, $this->decoder->decode('{"":"Bernhard"}')); + self::assertEquals($data, $this->decoder->decode('{"":"Bernhard"}')); } - public function testDecodeMagicEmptyPropertyAfter71() + public function testDecodeMagicEmptyPropertyAfter71(): void { - if (version_compare(PHP_VERSION, '7.1.0', '<')) { - $this->markTestSkipped('PHP >= 7.1.0 only'); - - return; - } - $data = (object) array('_empty_' => 'Bernhard'); - $this->assertEquals($data, $this->decoder->decode('{"_empty_":"Bernhard"}')); + self::assertEquals($data, $this->decoder->decode('{"_empty_":"Bernhard"}')); } - public function testDecodeMagicEmptyPropertyBefore71() - { - if (version_compare(PHP_VERSION, '7.1.0', '>=')) { - $this->markTestSkipped('PHP < 7.1.0 only'); - - return; - } - - $data = (object) array('a' => 'b', '_empty_' => 'Bernhard', 'c' => 'd'); - - $this->assertEquals($data, $this->decoder->decode('{"a":"b","":"Bernhard","c":"d"}')); - } - - public function provideInvalidObjectDecoding() + public function provideInvalidObjectDecoding(): array { return array( array(JsonDecoder::STRING), @@ -207,18 +180,18 @@ public function provideInvalidObjectDecoding() /** * @dataProvider provideInvalidObjectDecoding - * @expectedException \InvalidArgumentException */ - public function testFailIfInvalidObjectDecoding($invalidDecoding) + public function testFailIfInvalidObjectDecoding($invalidDecoding): void { + $this->expectException(InvalidArgumentException::class); + $this->decoder->setObjectDecoding($invalidDecoding); } - /** - * @expectedException \InvalidArgumentException - */ - public function testSchemaNotSupportedForArrays() + public function testSchemaNotSupportedForArrays(): void { + $this->expectException(InvalidArgumentException::class); + $this->decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY); $this->decoder->decode('{ "name": "Bernhard" }', $this->schemaObject); @@ -226,81 +199,79 @@ public function testSchemaNotSupportedForArrays() /** * JSON_ERROR_DEPTH. - * - * @expectedException \Webmozart\Json\DecodingFailedException - * @expectedExceptionCode 1 */ - public function testMaxDepth1Exceeded() + public function testMaxDepth1Exceeded(): void { + $this->expectException(DecodingFailedException::class); + $this->expectExceptionCode(1); + $this->decoder->setMaxDepth(1); $this->decoder->decode('{ "name": "Bernhard" }'); } - public function testMaxDepth1NotExceeded() + public function testMaxDepth1NotExceeded(): void { $this->decoder->setMaxDepth(1); - $this->assertSame('Bernhard', $this->decoder->decode('"Bernhard"')); + self::assertSame('Bernhard', $this->decoder->decode('"Bernhard"')); } /** * JSON_ERROR_DEPTH. - * - * @expectedException \Webmozart\Json\DecodingFailedException - * @expectedExceptionCode 1 */ - public function testMaxDepth2Exceeded() + public function testMaxDepth2Exceeded(): void { + $this->expectException(DecodingFailedException::class); + $this->expectExceptionCode(1); + $this->decoder->setMaxDepth(2); $this->decoder->decode('{ "key": { "name": "Bernhard" } }'); } - public function testMaxDepth2NotExceeded() + public function testMaxDepth2NotExceeded(): void { $this->decoder->setMaxDepth(2); $decoded = $this->decoder->decode('{ "name": "Bernhard" }'); - $this->assertEquals((object) array('name' => 'Bernhard'), $decoded); + self::assertEquals((object) array('name' => 'Bernhard'), $decoded); } - /** - * @expectedException \InvalidArgumentException - */ - public function testMaxDepthMustBeInteger() + public function testMaxDepthMustBeInteger(): void { + $this->expectException(InvalidArgumentException::class); + $this->decoder->setMaxDepth('foo'); } - /** - * @expectedException \InvalidArgumentException - */ - public function testMaxDepthMustBeOneOrGreater() + public function testMaxDepthMustBeOneOrGreater(): void { + $this->expectException(InvalidArgumentException::class); + $this->decoder->setMaxDepth(0); } - public function testDecodeBigIntAsFloat() + public function testDecodeBigIntAsFloat(): void { $this->decoder->setBigIntDecoding(JsonDecoder::FLOAT); $decoded = $this->decoder->decode('12312512423531123'); - $this->assertEquals(12312512423531123.0, $decoded); + self::assertEquals(12312512423531123.0, $decoded); } - public function testDecodeBigIntAsString() + public function testDecodeBigIntAsString(): void { $this->decoder->setBigIntDecoding(JsonDecoder::STRING); $decoded = $this->decoder->decode('12312512423531123'); - $this->assertEquals('12312512423531123', $decoded); + self::assertEquals('12312512423531123', $decoded); } - public function provideInvalidBigIntDecoding() + public function provideInvalidBigIntDecoding(): array { return array( array(JsonDecoder::OBJECT), @@ -311,26 +282,32 @@ public function provideInvalidBigIntDecoding() /** * @dataProvider provideInvalidBigIntDecoding - * @expectedException \InvalidArgumentException */ - public function testFailIfInvalidBigIntDecoding($invalidDecoding) + public function testFailIfInvalidBigIntDecoding($invalidDecoding): void { + $this->expectException(InvalidArgumentException::class); + $this->decoder->setBigIntDecoding($invalidDecoding); } - public function testDecodeFile() + public function testDecodeFile(): void { $data = $this->decoder->decodeFile($this->fixturesDir.'/valid.json'); - $this->assertInstanceOf('\stdClass', $data); - $this->assertObjectHasAttribute('name', $data); - $this->assertSame('Bernhard', $data->name); + self::assertInstanceOf(stdClass::class, $data); + self::assertObjectHasAttribute('name', $data); + self::assertSame('Bernhard', $data->name); } - public function testDecodeFileFailsIfNotReadable() + /** + * This test fails on my docker php:7.3-cli docker container + * The chmod sets 0000 on the file but `file_get_contents` still reads the content. + * However this test is successful on Travis. + */ + public function testDecodeFileFailsIfNotReadable(): void { if ('\\' === DIRECTORY_SEPARATOR) { - $this->markTestSkipped('Cannot deny read access on Windows.'); + self::markTestSkipped('Cannot deny read access on Windows.'); } $tempFile = tempnam(sys_get_temp_dir(), 'JsonDecoderTest'); @@ -339,71 +316,47 @@ public function testDecodeFileFailsIfNotReadable() chmod($tempFile, 0000); // Test that the file name is present in the output. - $this->setExpectedException( - '\Webmozart\Json\IOException', - $tempFile - ); + $this->expectException(IOException::class); + $this->expectExceptionMessage($tempFile); $this->decoder->decodeFile($tempFile); } /** * Test that the file name is present in the output. - * - * @expectedException \Webmozart\Json\FileNotFoundException - * @expectedExceptionMessage bogus.json */ - public function testDecodeFileFailsIfNotFound() + public function testDecodeFileFailsIfNotFound(): void { + $this->expectException(FileNotFoundException::class); + $this->expectExceptionMessage('bogus.json'); + $this->decoder->decodeFile($this->fixturesDir.'/bogus.json'); } /** * Test that the file name is present in the output. - * - * @expectedException \Webmozart\Json\ValidationFailedException - * @expectedExceptionMessage invalid.json */ - public function testDecodeFileFailsIfValidationFailsWithSchemaFile() + public function testDecodeFileFailsIfValidationFailsWithSchemaObject(): void { - $this->decoder->decodeFile($this->fixturesDir.'/invalid.json', $this->schemaFile); - } + $this->expectException(ValidationFailedException::class); + $this->expectExceptionMessage('invalid.json'); - /** - * Test that the file name is present in the output. - * - * @expectedException \Webmozart\Json\ValidationFailedException - * @expectedExceptionMessage invalid.json - */ - public function testDecodeFileFailsIfValidationFailsWithSchemaObject() - { $this->decoder->decodeFile($this->fixturesDir.'/invalid.json', $this->schemaObject); } /** * Test that the file name is present in the output. - * - * @expectedException \Webmozart\Json\DecodingFailedException - * @expectedExceptionMessage win-1258.json - * @expectedExceptionCode 5 */ - public function testDecodeFileFailsIfNotUtf8() + public function testDecodeFileFailsIfNotUtf8(): void { if (defined('JSON_C_VERSION')) { - $this->markTestSkipped('This error is not reported when using JSONC.'); + self::markTestSkipped('This error is not reported when using JSONC.'); } - $this->decoder->decodeFile($this->fixturesDir.'/win-1258.json'); - } + $this->expectException(DecodingFailedException::class); + $this->expectExceptionMessage('win-1258.json'); + $this->expectExceptionCode(5); - /** - * Test that the file name is present in the output. - * - * @expectedException \Webmozart\Json\InvalidSchemaException - * @expectedExceptionMessage valid.json - */ - public function testDecodeFileFailsIfSchemaInvalid() - { - $this->decoder->decodeFile($this->fixturesDir.'/valid.json', 'bogus.json'); + $this->decoder->decodeFile($this->fixturesDir.'/win-1258.json'); } } diff --git a/tests/JsonEncoderTest.php b/tests/JsonEncoderTest.php index 0093bb7..b1f23a9 100644 --- a/tests/JsonEncoderTest.php +++ b/tests/JsonEncoderTest.php @@ -11,17 +11,22 @@ namespace Webmozart\Json\Tests; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; use Symfony\Component\Filesystem\Filesystem; +use Webmozart\Json\EncodingFailedException; +use Webmozart\Json\IOException; use Webmozart\Json\JsonEncoder; +use Webmozart\Json\ValidationFailedException; /** * @since 1.0 * * @author Bernhard Schussek */ -class JsonEncoderTest extends \PHPUnit_Framework_TestCase +class JsonEncoderTest extends TestCase { - const BINARY_INPUT = "\xff\xf0"; + private const BINARY_INPUT = "\xff\xf0"; /** * @var JsonEncoder @@ -38,7 +43,7 @@ class JsonEncoderTest extends \PHPUnit_Framework_TestCase private $tempFile; - public function provideValues() + public function provideValues(): array { return array( array(0, '0'), @@ -57,9 +62,9 @@ public function provideValues() ); } - protected function setUp() + protected function setUp(): void { - while (false === @mkdir($this->tempDir = sys_get_temp_dir().'/webmozart-JsonEncoderTest'.rand(10000, 99999), 0777, true)) { + while (false === @mkdir($this->tempDir = sys_get_temp_dir().'/webmozart-JsonEncoderTest'.random_int(10000, 99999), 0777, true)) { } $this->encoder = new JsonEncoder(); @@ -69,7 +74,7 @@ protected function setUp() $this->tempFile = $this->tempDir.'/data.json'; } - protected function tearDown() + protected function tearDown(): void { $filesystem = new Filesystem(); @@ -81,141 +86,101 @@ protected function tearDown() /** * @dataProvider provideValues */ - public function testEncode($value, $json) + public function testEncode($value, $json): void { - $this->assertSame($json, $this->encoder->encode($value)); + self::assertSame($json, $this->encoder->encode($value)); } - public function testEncodeWithSchemaFile() + public function testEncodeWithSchemaFile(): void { $data = (object) array('name' => 'Bernhard'); - $this->assertSame('{"name":"Bernhard"}', $this->encoder->encode($data, $this->schemaFile)); + self::assertSame('{"name":"Bernhard"}', $this->encoder->encode($data, $this->schemaFile)); } - public function testEncodeWithSchemaObject() + public function testEncodeWithSchemaObject(): void { $data = (object) array('name' => 'Bernhard'); - $this->assertSame('{"name":"Bernhard"}', $this->encoder->encode($data, $this->schemaObject)); + self::assertSame('{"name":"Bernhard"}', $this->encoder->encode($data, $this->schemaObject)); } - /** - * @expectedException \Webmozart\Json\ValidationFailedException - */ - public function testEncodeFailsIfValidationFailsWithSchemaFile() + public function testEncodeFailsIfValidationFailsWithSchemaObject(): void { - $this->encoder->encode('foobar', $this->schemaFile); - } + $this->expectException(ValidationFailedException::class); - /** - * @expectedException \Webmozart\Json\ValidationFailedException - */ - public function testEncodeFailsIfValidationFailsWithSchemaObject() - { $this->encoder->encode('foobar', $this->schemaObject); } - public function testEncodeUtf8() + public function testEncodeUtf8(): void { $data = (object) array('name' => 'Bérnhard'); - $this->assertSame('{"name":"B\u00e9rnhard"}', $this->encoder->encode($data)); + self::assertSame('{"name":"B\u00e9rnhard"}', $this->encoder->encode($data)); } /** * JSON_ERROR_UTF8. - * - * @expectedException \Webmozart\Json\EncodingFailedException - * @expectedExceptionCode 5 */ - public function testEncodeFailsIfNonUtf8() + public function testEncodeFailsIfNonUtf8(): void { - if (version_compare(PHP_VERSION, '5.5.0', '<')) { - $this->markTestSkipped('PHP >= 5.5.0 only'); - - return; - } + $this->expectException(EncodingFailedException::class); + $this->expectExceptionCode(5); $this->encoder->encode(file_get_contents($this->fixturesDir.'/win-1258.json')); } /** * JSON_ERROR_UTF8. - * - * @expectedException \Webmozart\Json\EncodingFailedException - * @expectedExceptionCode 5 */ - public function testEncodeFailsForBinaryValue() + public function testEncodeFailsForBinaryValue(): void { + $this->expectException(EncodingFailedException::class); + $this->expectExceptionCode(5); + $this->encoder->encode(self::BINARY_INPUT); } - public function testEncodeEmptyArrayKey() + public function testEncodeEmptyArrayKey(): void { $data = array('' => 'Bernhard'); - $this->assertSame('{"":"Bernhard"}', $this->encoder->encode($data)); + self::assertSame('{"":"Bernhard"}', $this->encoder->encode($data)); } - public function testEncodeEmptyProperty() + public function testEncodeEmptyProperty(): void { - if (version_compare(PHP_VERSION, '7.1.0', '<')) { - $this->markTestSkipped('PHP >= 7.1.0 only'); - - return; - } - $data = (object) array('' => 'Bernhard'); - $this->assertSame('{"":"Bernhard"}', $this->encoder->encode($data)); + self::assertSame('{"":"Bernhard"}', $this->encoder->encode($data)); } - public function testEncodeMagicEmptyPropertyAfter71() + public function testEncodeMagicEmptyPropertyAfter71(): void { - if (version_compare(PHP_VERSION, '7.1.0', '<')) { - $this->markTestSkipped('PHP >= 7.1.0 only'); - - return; - } - $data = (object) array('_empty_' => 'Bernhard'); - $this->assertSame('{"_empty_":"Bernhard"}', $this->encoder->encode($data)); + self::assertSame('{"_empty_":"Bernhard"}', $this->encoder->encode($data)); } - public function testEncodeMagicEmptyPropertyBefore71() - { - if (version_compare(PHP_VERSION, '7.1.0', '>=')) { - $this->markTestSkipped('PHP < 7.1.0 only'); - - return; - } - - $data = (object) array('a' => 'b', '_empty_' => 'Bernhard', 'c' => 'd'); - - $this->assertSame('{"a":"b","":"Bernhard","c":"d"}', $this->encoder->encode($data)); - } - - public function testEncodeArrayAsArray() + public function testEncodeArrayAsArray(): void { $data = array('one', 'two'); $this->encoder->setArrayEncoding(JsonEncoder::JSON_ARRAY); - $this->assertSame('["one","two"]', $this->encoder->encode($data)); + self::assertSame('["one","two"]', $this->encoder->encode($data)); } - public function testEncodeArrayAsObject() + public function testEncodeArrayAsObject(): void { $data = array('one', 'two'); $this->encoder->setArrayEncoding(JsonEncoder::JSON_OBJECT); - $this->assertSame('{"0":"one","1":"two"}', $this->encoder->encode($data)); + self::assertSame('{"0":"one","1":"two"}', $this->encoder->encode($data)); } - public function provideInvalidArrayEncoding() + public function provideInvalidArrayEncoding(): array { return array( array(JsonEncoder::JSON_NUMBER), @@ -226,41 +191,42 @@ public function provideInvalidArrayEncoding() /** * @dataProvider provideInvalidArrayEncoding - * @expectedException \InvalidArgumentException */ - public function testFailIfInvalidArrayEncoding($invalidEncoding) + public function testFailIfInvalidArrayEncoding($invalidEncoding): void { + $this->expectException(InvalidArgumentException::class); + $this->encoder->setArrayEncoding($invalidEncoding); } - public function testEncodeNumericAsString() + public function testEncodeNumericAsString(): void { $data = '12345'; $this->encoder->setNumericEncoding(JsonEncoder::JSON_STRING); - $this->assertSame('"12345"', $this->encoder->encode($data)); + self::assertSame('"12345"', $this->encoder->encode($data)); } - public function testEncodeIntegerStringAsInteger() + public function testEncodeIntegerStringAsInteger(): void { $data = '12345'; $this->encoder->setNumericEncoding(JsonEncoder::JSON_NUMBER); - $this->assertSame('12345', $this->encoder->encode($data)); + self::assertSame('12345', $this->encoder->encode($data)); } - public function testEncodeIntegerFloatAsFloat() + public function testEncodeIntegerFloatAsFloat(): void { $data = '123.45'; $this->encoder->setNumericEncoding(JsonEncoder::JSON_NUMBER); - $this->assertSame('123.45', $this->encoder->encode($data)); + self::assertSame('123.45', $this->encoder->encode($data)); } - public function provideInvalidNumericEncoding() + public function provideInvalidNumericEncoding(): array { return array( array(JsonEncoder::JSON_ARRAY), @@ -271,226 +237,206 @@ public function provideInvalidNumericEncoding() /** * @dataProvider provideInvalidNumericEncoding - * @expectedException \InvalidArgumentException */ - public function testFailIfInvalidNumericEncoding($invalidEncoding) + public function testFailIfInvalidNumericEncoding($invalidEncoding): void { + $this->expectException(InvalidArgumentException::class); + $this->encoder->setNumericEncoding($invalidEncoding); } - public function testGtLtEscaoed() + public function testGtLtEscaped(): void { $this->encoder->setEscapeGtLt(true); - $this->assertSame('"\u003C\u003E"', $this->encoder->encode('<>')); + self::assertSame('"\u003C\u003E"', $this->encoder->encode('<>')); } - public function testGtLtNotEscaoed() + public function testGtLtNotEscaped(): void { $this->encoder->setEscapeGtLt(false); - $this->assertSame('"<>"', $this->encoder->encode('<>')); + self::assertSame('"<>"', $this->encoder->encode('<>')); } - public function testAmpersandEscaped() + public function testAmpersandEscaped(): void { $this->encoder->setEscapeAmpersand(true); - $this->assertSame('"\u0026"', $this->encoder->encode('&')); + self::assertSame('"\u0026"', $this->encoder->encode('&')); } - public function testAmpersandNotEscaped() + public function testAmpersandNotEscaped(): void { $this->encoder->setEscapeAmpersand(false); - $this->assertSame('"&"', $this->encoder->encode('&')); + self::assertSame('"&"', $this->encoder->encode('&')); } - public function testSingleQuoteEscaped() + public function testSingleQuoteEscaped(): void { $this->encoder->setEscapeSingleQuote(true); - $this->assertSame('"\u0027"', $this->encoder->encode("'")); + self::assertSame('"\u0027"', $this->encoder->encode("'")); } - public function testSingleQuoteNotEscaped() + public function testSingleQuoteNotEscaped(): void { $this->encoder->setEscapeSingleQuote(false); - $this->assertSame('"\'"', $this->encoder->encode("'")); + self::assertSame('"\'"', $this->encoder->encode("'")); } - public function testDoubleQuoteEscaped() + public function testDoubleQuoteEscaped(): void { $this->encoder->setEscapeDoubleQuote(true); - $this->assertSame('"\u0022"', $this->encoder->encode('"')); + self::assertSame('"\u0022"', $this->encoder->encode('"')); } - public function testDoubleQuoteNotEscaped() + public function testDoubleQuoteNotEscaped(): void { $this->encoder->setEscapeDoubleQuote(false); - $this->assertSame('"\""', $this->encoder->encode('"')); + self::assertSame('"\""', $this->encoder->encode('"')); } - public function testSlashEscaped() + public function testSlashEscaped(): void { $this->encoder->setEscapeSlash(true); - $this->assertSame('"\\/"', $this->encoder->encode('/')); + self::assertSame('"\\/"', $this->encoder->encode('/')); } - public function testSlashNotEscaped() + public function testSlashNotEscaped(): void { $this->encoder->setEscapeSlash(false); - $this->assertSame('"/"', $this->encoder->encode('/')); + self::assertSame('"/"', $this->encoder->encode('/')); } - public function testUnicodeEscaped() + public function testUnicodeEscaped(): void { $this->encoder->setEscapeUnicode(true); - $this->assertSame('"\u00fc"', $this->encoder->encode('ü')); + self::assertSame('"\u00fc"', $this->encoder->encode('ü')); } - public function testUnicodeNotEscaped() + public function testUnicodeNotEscaped(): void { - if (version_compare(PHP_VERSION, '5.4.0', '<')) { - $this->markTestSkipped('PHP >= 5.4.0 only'); - - return; - } - $this->encoder->setEscapeUnicode(false); - $this->assertSame('"ü"', $this->encoder->encode('ü')); + self::assertSame('"ü"', $this->encoder->encode('ü')); } /** * JSON_ERROR_DEPTH. - * - * @expectedException \Webmozart\Json\EncodingFailedException - * @expectedExceptionCode 1 */ - public function testMaxDepth1Exceeded() + public function testMaxDepth1Exceeded(): void { - if (version_compare(PHP_VERSION, '5.5.0', '<')) { - $this->markTestSkipped('PHP >= 5.5.0 only'); - - return; - } + $this->expectException(EncodingFailedException::class); + $this->expectExceptionCode(1); $this->encoder->setMaxDepth(1); $this->encoder->encode((object) array('name' => 'Bernhard')); } - public function testMaxDepth1NotExceeded() + public function testMaxDepth1NotExceeded(): void { $this->encoder->setMaxDepth(1); - $this->assertSame('"Bernhard"', $this->encoder->encode('Bernhard')); + self::assertSame('"Bernhard"', $this->encoder->encode('Bernhard')); } /** * JSON_ERROR_DEPTH. - * - * @expectedException \Webmozart\Json\EncodingFailedException - * @expectedExceptionCode 1 */ - public function testMaxDepth2Exceeded() + public function testMaxDepth2Exceeded(): void { - if (version_compare(PHP_VERSION, '5.5.0', '<')) { - $this->markTestSkipped('PHP >= 5.5.0 only'); - - return; - } + $this->expectException(EncodingFailedException::class); + $this->expectExceptionCode(1); $this->encoder->setMaxDepth(2); $this->encoder->encode((object) array('key' => (object) array('name' => 'Bernhard'))); } - public function testMaxDepth2NotExceeded() + public function testMaxDepth2NotExceeded(): void { $this->encoder->setMaxDepth(2); - $this->assertSame('{"name":"Bernhard"}', $this->encoder->encode((object) array('name' => 'Bernhard'))); + self::assertSame('{"name":"Bernhard"}', $this->encoder->encode((object) array('name' => 'Bernhard'))); } - /** - * @expectedException \InvalidArgumentException - */ - public function testMaxDepthMustBeInteger() + public function testMaxDepthMustBeInteger(): void { + $this->expectException(InvalidArgumentException::class); + $this->encoder->setMaxDepth('foo'); } - /** - * @expectedException \InvalidArgumentException - */ - public function testMaxDepthMustBeOneOrGreater() + public function testMaxDepthMustBeOneOrGreater(): void { + $this->expectException(InvalidArgumentException::class); + $this->encoder->setMaxDepth(0); } - public function testPrettyPrinting() + public function testPrettyPrinting(): void { - if (version_compare(PHP_VERSION, '5.4.0', '<')) { - $this->markTestSkipped('PHP >= 5.4.0 only'); - - return; - } - $this->encoder->setPrettyPrinting(true); - $this->assertSame("{\n \"name\": \"Bernhard\"\n}", $this->encoder->encode((object) array('name' => 'Bernhard'))); + self::assertSame("{\n \"name\": \"Bernhard\"\n}", $this->encoder->encode((object) array('name' => 'Bernhard'))); } - public function testNoPrettyPrinting() + public function testNoPrettyPrinting(): void { $this->encoder->setPrettyPrinting(false); - $this->assertSame('{"name":"Bernhard"}', $this->encoder->encode((object) array('name' => 'Bernhard'))); + self::assertSame('{"name":"Bernhard"}', $this->encoder->encode((object) array('name' => 'Bernhard'))); } - public function testTerminateWithLineFeed() + public function testTerminateWithLineFeed(): void { $this->encoder->setTerminateWithLineFeed(true); - $this->assertSame('{"name":"Bernhard"}'."\n", $this->encoder->encode((object) array('name' => 'Bernhard'))); + self::assertSame('{"name":"Bernhard"}'."\n", $this->encoder->encode((object) array('name' => 'Bernhard'))); } - public function testDoNotTerminateWithLineFeed() + public function testDoNotTerminateWithLineFeed(): void { $this->encoder->setTerminateWithLineFeed(false); - $this->assertSame('{"name":"Bernhard"}', $this->encoder->encode((object) array('name' => 'Bernhard'))); + self::assertSame('{"name":"Bernhard"}', $this->encoder->encode((object) array('name' => 'Bernhard'))); } - public function testEncodeFile() + public function testEncodeFile(): void { $data = (object) array('name' => 'Bernhard'); $this->encoder->encodeFile($data, $this->tempFile); - $this->assertFileExists($this->tempFile); - $this->assertSame('{"name":"Bernhard"}', file_get_contents($this->tempFile)); + self::assertFileExists($this->tempFile); + self::assertSame('{"name":"Bernhard"}', file_get_contents($this->tempFile)); } - public function testEncodeFileCreatesMissingDirectories() + public function testEncodeFileCreatesMissingDirectories(): void { $data = (object) array('name' => 'Bernhard'); $this->encoder->encodeFile($data, $this->tempDir.'/sub/data.json'); - $this->assertFileExists($this->tempDir.'/sub/data.json'); - $this->assertSame('{"name":"Bernhard"}', file_get_contents($this->tempDir.'/sub/data.json')); + self::assertFileExists($this->tempDir.'/sub/data.json'); + self::assertSame('{"name":"Bernhard"}', file_get_contents($this->tempDir.'/sub/data.json')); } - public function testEncodeFileFailsIfNotWritable() + /** + * This test fails on my docker php:7.3-cli docker container + * The chmod sets 0000 on the file but `file_get_contents` still reads the content. + * However this test is successful on Travis. + */ + public function testEncodeFileFailsIfNotWritable(): void { $data = (object) array('name' => 'Bernhard'); @@ -498,50 +444,27 @@ public function testEncodeFileFailsIfNotWritable() chmod($this->tempFile, 0400); // Test that the file name is present in the output. - $this->setExpectedException( - '\Webmozart\Json\IOException', - $this->tempFile - ); + $this->expectException(IOException::class); + $this->expectExceptionMessage($this->tempFile); $this->encoder->encodeFile($data, $this->tempFile); } - public function testEncodeFileFailsIfValidationFailsWithSchemaFile() + public function testEncodeFileFailsIfValidationFailsWithSchemaObject(): void { // Test that the file name is present in the output. - $this->setExpectedException( - '\Webmozart\Json\ValidationFailedException', - $this->tempFile - ); - - $this->encoder->encodeFile('foobar', $this->tempFile, $this->schemaFile); - } - - public function testEncodeFileFailsIfValidationFailsWithSchemaObject() - { - // Test that the file name is present in the output. - $this->setExpectedException( - '\Webmozart\Json\ValidationFailedException', - $this->tempFile - ); + $this->expectException(ValidationFailedException::class); + $this->expectExceptionMessage($this->tempFile); $this->encoder->encodeFile('foobar', $this->tempFile, $this->schemaObject); } - public function testEncodeFileFailsIfNonUtf8() + public function testEncodeFileFailsIfNonUtf8(): void { - if (version_compare(PHP_VERSION, '5.5.0', '<')) { - $this->markTestSkipped('PHP >= 5.5.0 only'); - - return; - } - // Test that the file name is present in the output. - $this->setExpectedException( - '\Webmozart\Json\EncodingFailedException', - $this->tempFile, - 5 - ); + $this->expectException(EncodingFailedException::class); + $this->expectExceptionMessage($this->tempFile); + $this->expectExceptionCode(5); $this->encoder->encodeFile(file_get_contents($this->fixturesDir.'/win-1258.json'), $this->tempFile); diff --git a/tests/JsonValidatorTest.php b/tests/JsonValidatorTest.php deleted file mode 100644 index a711d1b..0000000 --- a/tests/JsonValidatorTest.php +++ /dev/null @@ -1,250 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Webmozart\Json\Tests; - -use JsonSchema\Uri\Retrievers\PredefinedArray; -use JsonSchema\Uri\UriRetriever; -use Webmozart\Json\JsonValidator; - -/** - * @since 1.0 - * - * @author Bernhard Schussek - */ -class JsonValidatorTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var JsonValidator - */ - private $validator; - - private $fixturesDir; - - private $schemaFile; - - private $schemaObject; - - protected function setUp() - { - $this->validator = new JsonValidator(); - $this->fixturesDir = strtr(__DIR__.'/Fixtures', '\\', '/'); - $this->schemaFile = $this->fixturesDir.'/schema.json'; - $this->schemaObject = json_decode(file_get_contents($this->schemaFile)); - } - - public function testValidateWithSchemaFile() - { - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard'), - $this->schemaFile - ); - - $this->assertCount(0, $errors); - } - - public function testValidateWithSchemaFileInPhar() - { - // Work-around for https://bugs.php.net/bug.php?id=71368: - // "format": "uri" validation removed for "id" field in meta-schema.json - - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard'), - 'phar://'.$this->fixturesDir.'/schema.phar/schema.json' - ); - - $this->assertCount(0, $errors); - } - - public function testValidateWithSchemaObject() - { - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard'), - $this->schemaObject - ); - - $this->assertCount(0, $errors); - } - - public function testValidateWithSchemaField() - { - $uriRetriever = new UriRetriever(); - $uriRetriever->setUriRetriever(new PredefinedArray(array( - 'http://webmozart.io/fixtures/schema' => file_get_contents(__DIR__.'/Fixtures/schema.json'), - ))); - - $this->validator = new JsonValidator(null, $uriRetriever); - - $errors = $this->validator->validate((object) array( - '$schema' => 'http://webmozart.io/fixtures/schema', - 'name' => 'Bernhard', - )); - - $this->assertCount(0, $errors); - } - - public function testValidateWithReferences() - { - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard', 'has-coffee' => true), - $this->fixturesDir.'/schema-refs.json' - ); - - $this->assertCount(0, $errors); - } - - public function testValidateWithExternalReferences() - { - $uriRetriever = new UriRetriever(); - $uriRetriever->setUriRetriever(new PredefinedArray(array( - 'http://webmozart.io/fixtures/schema-refs' => file_get_contents(__DIR__.'/Fixtures/schema-refs.json'), - 'file://'.$this->fixturesDir.'/schema-external-refs.json' => file_get_contents(__DIR__.'/Fixtures/schema-external-refs.json'), - ))); - - $this->validator = new JsonValidator(null, $uriRetriever); - - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard', 'has-coffee' => true), - $this->fixturesDir.'/schema-external-refs.json' - ); - - $this->assertCount(0, $errors); - } - - public function testValidateFailsIfValidationFailsWithSchemaFile() - { - $errors = $this->validator->validate('foobar', $this->schemaFile); - - $this->assertCount(1, $errors); - } - - public function testValidateFailsIfValidationFailsWithSchemaObject() - { - $errors = $this->validator->validate('foobar', $this->schemaObject); - - $this->assertCount(1, $errors); - } - - public function testValidateFailsIfValidationFailsWithReferences() - { - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard', 'has-coffee' => null), - $this->fixturesDir.'/schema-refs.json' - ); - - $this->assertGreaterThan(1, count($errors)); - } - - public function testValidateFailsIfValidationFailsWithExternalReferences() - { - $uriRetriever = new UriRetriever(); - $uriRetriever->setUriRetriever(new PredefinedArray(array( - 'http://webmozart.io/fixtures/schema-refs' => file_get_contents(__DIR__.'/Fixtures/schema-refs.json'), - 'file://'.$this->fixturesDir.'/schema-external-refs.json' => file_get_contents(__DIR__.'/Fixtures/schema-external-refs.json'), - ))); - - $this->validator = new JsonValidator(null, $uriRetriever); - - $errors = $this->validator->validate( - (object) array('name' => 'Bernhard', 'has-coffee' => null), - $this->fixturesDir.'/schema-external-refs.json' - ); - - $this->assertGreaterThan(1, count($errors)); - } - - /** - * Test that the file name is mentioned in the output. - * - * @expectedException \Webmozart\Json\InvalidSchemaException - * @expectedExceptionMessage bogus.json - */ - public function testValidateFailsIfSchemaFileNotFound() - { - $this->validator->validate((object) array('name' => 'Bernhard'), __DIR__.'/bogus.json'); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfSchemaNeitherStringNorObject() - { - $this->validator->validate((object) array('name' => 'Bernhard'), 12345); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfSchemaFileContainsNoObject() - { - $this->validator->validate( - (object) array('name' => 'Bernhard'), - $this->fixturesDir.'/schema-no-object.json' - ); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfSchemaFileInvalid() - { - $this->validator->validate( - (object) array('name' => 'Bernhard'), - $this->fixturesDir.'/schema-invalid.json' - ); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfSchemaObjectInvalid() - { - $this->validator->validate( - (object) array('name' => 'Bernhard'), - (object) array('id' => 12345) - ); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfInvalidSchemaNotRecognized() - { - // justinrainbow/json-schema cannot validate "anyOf", so the following - // will load the schema successfully and fail when the file is validated - // against the schema - $this->validator->validate( - (object) array('name' => 'Bernhard'), - (object) array('type' => 12345) - ); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfMissingSchema() - { - $this->validator->validate( - (object) array('name' => 'Bernhard') - ); - } - - /** - * @expectedException \Webmozart\Json\InvalidSchemaException - */ - public function testValidateFailsIfInvalidSchemaType() - { - $this->validator->validate( - (object) array('name' => 'Bernhard'), - 1234 - ); - } -} diff --git a/tests/Migration/MigratingConverterTest.php b/tests/Migration/MigratingConverterTest.php index 9998803..e86eab8 100644 --- a/tests/Migration/MigratingConverterTest.php +++ b/tests/Migration/MigratingConverterTest.php @@ -11,28 +11,30 @@ namespace Webmozart\Json\Tests\Migration; -use PHPUnit_Framework_Assert; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use stdClass; +use Webmozart\Json\Conversion\ConversionFailedException; use Webmozart\Json\Conversion\JsonConverter; use Webmozart\Json\Migration\MigratingConverter; use Webmozart\Json\Migration\MigrationManager; +use Webmozart\Json\Migration\UnsupportedVersionException; /** * @since 1.3 * * @author Bernhard Schussek */ -class MigratingConverterTest extends PHPUnit_Framework_TestCase +class MigratingConverterTest extends TestCase { /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonConverter + * @var MockObject|JsonConverter */ private $innerConverter; /** - * @var PHPUnit_Framework_MockObject_MockObject|MigrationManager + * @var MockObject|MigrationManager */ private $migrationManager; @@ -41,19 +43,19 @@ class MigratingConverterTest extends PHPUnit_Framework_TestCase */ private $converter; - protected function setUp() + protected function setUp(): void { - $this->migrationManager = $this->getMockBuilder('Webmozart\Json\Migration\MigrationManager') + $this->migrationManager = $this->getMockBuilder(MigrationManager::class) ->disableOriginalConstructor() ->getMock(); - $this->migrationManager->expects($this->any()) + $this->migrationManager->expects(self::any()) ->method('getKnownVersions') ->willReturn(array('0.9', '1.0')); - $this->innerConverter = $this->getMock('Webmozart\Json\Conversion\JsonConverter'); + $this->innerConverter = $this->createMock(JsonConverter::class); $this->converter = new MigratingConverter($this->innerConverter, '1.0', $this->migrationManager); } - public function testToJsonDowngradesIfLowerVersion() + public function testToJsonDowngradesIfLowerVersion(): void { $options = array( 'inner_option' => 'value', @@ -69,26 +71,26 @@ public function testToJsonDowngradesIfLowerVersion() 'downgraded' => true, ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($beforeMigration); - $this->migrationManager->expects($this->once()) + $this->migrationManager->expects(self::once()) ->method('migrate') ->willReturnCallback(function (stdClass $jsonData, $targetVersion) use ($beforeMigration) { // with() in combination with argument cloning doesn't work, // since we *want* to modify the original data (not the clone) below - PHPUnit_Framework_Assert::assertEquals($beforeMigration, $jsonData); + Assert::assertEquals($beforeMigration, $jsonData); $jsonData->version = $targetVersion; $jsonData->downgraded = true; }); - $this->assertEquals($afterMigration, $this->converter->toJson('DATA', $options)); + self::assertEquals($afterMigration, $this->converter->toJson('DATA', $options)); } - public function testToJsonDoesNotMigrateCurrentVersion() + public function testToJsonDoesNotMigrateCurrentVersion(): void { $options = array( 'inner_option' => 'value', @@ -99,18 +101,18 @@ public function testToJsonDoesNotMigrateCurrentVersion() 'version' => '1.0', ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($jsonData); - $this->migrationManager->expects($this->never()) + $this->migrationManager->expects(self::never()) ->method('migrate'); - $this->assertEquals($jsonData, $this->converter->toJson('DATA', $options)); + self::assertEquals($jsonData, $this->converter->toJson('DATA', $options)); } - public function testToJsonDoesNotMigrateIfNoTargetVersion() + public function testToJsonDoesNotMigrateIfNoTargetVersion(): void { $options = array( 'inner_option' => 'value', @@ -120,47 +122,45 @@ public function testToJsonDoesNotMigrateIfNoTargetVersion() 'version' => '1.0', ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($jsonData); - $this->migrationManager->expects($this->never()) + $this->migrationManager->expects(self::never()) ->method('migrate'); - $this->assertEquals($jsonData, $this->converter->toJson('DATA', $options)); + self::assertEquals($jsonData, $this->converter->toJson('DATA', $options)); } - /** - * @expectedException \Webmozart\Json\Migration\UnsupportedVersionException - */ - public function testToJsonFailsIfTargetVersionTooHigh() + public function testToJsonFailsIfTargetVersionTooHigh(): void { + $this->expectException(UnsupportedVersionException::class); + $this->converter->toJson('DATA', array('targetVersion' => '1.1')); } - /** - * @expectedException \Webmozart\Json\Conversion\ConversionFailedException - */ - public function testToJsonFailsIfNotAnObject() + public function testToJsonFailsIfNotAnObject(): void { + $this->expectException(ConversionFailedException::class); + $options = array( 'inner_option' => 'value', 'targetVersion' => '1.0', ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn('foobar'); - $this->migrationManager->expects($this->never()) + $this->migrationManager->expects(self::never()) ->method('migrate'); $this->converter->toJson('DATA', $options); } - public function testFromJsonUpgradesIfVersionTooLow() + public function testFromJsonUpgradesIfVersionTooLow(): void { $options = array( 'inner_option' => 'value', @@ -175,26 +175,26 @@ public function testFromJsonUpgradesIfVersionTooLow() 'upgraded' => true, ); - $this->migrationManager->expects($this->once()) + $this->migrationManager->expects(self::once()) ->method('migrate') ->willReturnCallback(function (stdClass $jsonData, $targetVersion) use ($beforeMigration) { - PHPUnit_Framework_Assert::assertEquals($beforeMigration, $jsonData); + Assert::assertEquals($beforeMigration, $jsonData); $jsonData->version = $targetVersion; $jsonData->upgraded = true; }); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('fromJson') ->with($afterMigration, $options) ->willReturn('DATA'); $result = $this->converter->fromJson(clone $beforeMigration, $options); - $this->assertSame('DATA', $result); + self::assertSame('DATA', $result); } - public function testFromJsonDoesNotMigrateCurrentVersion() + public function testFromJsonDoesNotMigrateCurrentVersion(): void { $options = array( 'inner_option' => 'value', @@ -204,24 +204,23 @@ public function testFromJsonDoesNotMigrateCurrentVersion() 'version' => '1.0', ); - $this->migrationManager->expects($this->never()) + $this->migrationManager->expects(self::never()) ->method('migrate'); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('fromJson') ->with($jsonData, $options) ->willReturn('DATA'); $result = $this->converter->fromJson(clone $jsonData, $options); - $this->assertSame('DATA', $result); + self::assertSame('DATA', $result); } - /** - * @expectedException \Webmozart\Json\Migration\UnsupportedVersionException - */ - public function testFromJsonFailsIfSourceVersionTooHigh() + public function testFromJsonFailsIfSourceVersionTooHigh(): void { + $this->expectException(UnsupportedVersionException::class); + $jsonData = (object) array( 'version' => '1.1', ); @@ -229,29 +228,27 @@ public function testFromJsonFailsIfSourceVersionTooHigh() $this->converter->fromJson($jsonData); } - /** - * @expectedException \Webmozart\Json\Conversion\ConversionFailedException - */ - public function testFromJsonFailsIfNotAnObject() + public function testFromJsonFailsIfNotAnObject(): void { - $this->migrationManager->expects($this->never()) + $this->expectException(ConversionFailedException::class); + + $this->migrationManager->expects(self::never()) ->method('migrate'); - $this->innerConverter->expects($this->never()) + $this->innerConverter->expects(self::never()) ->method('fromJson'); $this->converter->fromJson('foobar'); } - /** - * @expectedException \Webmozart\Json\Conversion\ConversionFailedException - */ - public function testFromJsonFailsIfVersionIsMissing() + public function testFromJsonFailsIfVersionIsMissing(): void { - $this->migrationManager->expects($this->never()) + $this->expectException(ConversionFailedException::class); + + $this->migrationManager->expects(self::never()) ->method('migrate'); - $this->innerConverter->expects($this->never()) + $this->innerConverter->expects(self::never()) ->method('fromJson'); $this->converter->fromJson((object) array()); diff --git a/tests/Migration/MigrationManagerTest.php b/tests/Migration/MigrationManagerTest.php index 9977650..5546d28 100644 --- a/tests/Migration/MigrationManagerTest.php +++ b/tests/Migration/MigrationManagerTest.php @@ -11,11 +11,12 @@ namespace Webmozart\Json\Tests\Migration; -use PHPUnit_Framework_Assert; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; use stdClass; use Webmozart\Json\Migration\JsonMigration; +use Webmozart\Json\Migration\MigrationFailedException; use Webmozart\Json\Migration\MigrationManager; use Webmozart\Json\Versioning\JsonVersioner; @@ -24,25 +25,25 @@ * * @author Bernhard Schussek */ -class MigrationManagerTest extends PHPUnit_Framework_TestCase +class MigrationManagerTest extends TestCase { /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonMigration + * @var MockObject|JsonMigration */ private $migration1; /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonMigration + * @var MockObject|JsonMigration */ private $migration2; /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonMigration + * @var MockObject|JsonMigration */ private $migration3; /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonVersioner + * @var MockObject|JsonVersioner */ private $versioner; @@ -51,12 +52,12 @@ class MigrationManagerTest extends PHPUnit_Framework_TestCase */ private $manager; - protected function setUp() + protected function setUp(): void { $this->migration1 = $this->createMigrationMock('0.8', '0.10'); $this->migration2 = $this->createMigrationMock('0.10', '1.0'); $this->migration3 = $this->createMigrationMock('1.0', '2.0'); - $this->versioner = $this->getMock('Webmozart\Json\Versioning\JsonVersioner'); + $this->versioner = $this->createMock(JsonVersioner::class); $this->manager = new MigrationManager(array( $this->migration1, $this->migration2, @@ -64,16 +65,16 @@ protected function setUp() ), $this->versioner); } - public function testMigrateUp() + public function testMigrateUp(): void { $data = (object) array('calls' => 0); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('0.8'); - $this->versioner->expects($this->exactly(3)) + $this->versioner->expects(self::exactly(3)) ->method('updateVersion') ->withConsecutive( array($data, '0.10'), @@ -81,130 +82,128 @@ public function testMigrateUp() array($data, '2.0') ); - $this->migration1->expects($this->once()) + $this->migration1->expects(self::once()) ->method('up') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(0, $data->calls); + Assert::assertSame(0, $data->calls); ++$data->calls; }); - $this->migration2->expects($this->once()) + $this->migration2->expects(self::once()) ->method('up') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(1, $data->calls); + Assert::assertSame(1, $data->calls); ++$data->calls; }); - $this->migration3->expects($this->once()) + $this->migration3->expects(self::once()) ->method('up') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(2, $data->calls); + Assert::assertSame(2, $data->calls); ++$data->calls; }); $this->manager->migrate($data, '2.0'); - $this->assertSame(3, $data->calls); + self::assertSame(3, $data->calls); } - public function testMigrateUpPartial() + public function testMigrateUpPartial(): void { $data = (object) array('calls' => 0); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('0.10'); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('updateVersion') ->with($data, '1.0'); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('up'); - $this->migration2->expects($this->once()) + $this->migration2->expects(self::once()) ->method('up') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(0, $data->calls); + Assert::assertSame(0, $data->calls); ++$data->calls; }); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('up'); $this->manager->migrate($data, '1.0'); - $this->assertSame(1, $data->calls); + self::assertSame(1, $data->calls); } - /** - * @expectedException \Webmozart\Json\Migration\MigrationFailedException - * @expectedExceptionMessage 0.5 - */ - public function testMigrateUpFailsIfNoMigrationForSourceVersion() + public function testMigrateUpFailsIfNoMigrationForSourceVersion(): void { + $this->expectException(MigrationFailedException::class); + $this->expectExceptionMessage('0.5'); + $data = (object) array(); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('0.5'); - $this->versioner->expects($this->never()) + $this->versioner->expects(self::never()) ->method('updateVersion'); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('up'); - $this->migration2->expects($this->never()) + $this->migration2->expects(self::never()) ->method('up'); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('up'); $this->manager->migrate($data, '0.10'); } - /** - * @expectedException \Webmozart\Json\Migration\MigrationFailedException - * @expectedExceptionMessage 1.2 - */ - public function testMigrateUpFailsIfNoMigrationForTargetVersion() + public function testMigrateUpFailsIfNoMigrationForTargetVersion(): void { + $this->expectException(MigrationFailedException::class); + $this->expectExceptionMessage('1.2'); + $data = (object) array('calls' => 0); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('0.10'); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('updateVersion') ->with($data, '1.0'); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('up'); - $this->migration2->expects($this->once()) + $this->migration2->expects(self::once()) ->method('up') ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(0, $data->calls); + Assert::assertSame(0, $data->calls); ++$data->calls; }); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('up'); $this->manager->migrate($data, '1.2'); } - public function testMigrateDown() + public function testMigrateDown(): void { $data = (object) array('calls' => 0); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('2.0'); - $this->versioner->expects($this->exactly(3)) + $this->versioner->expects(self::exactly(3)) ->method('updateVersion') ->withConsecutive( array($data, '1.0'), @@ -212,175 +211,173 @@ public function testMigrateDown() array($data, '0.8') ); - $this->migration3->expects($this->once()) + $this->migration3->expects(self::once()) ->method('down') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(0, $data->calls); + Assert::assertSame(0, $data->calls); ++$data->calls; }); - $this->migration2->expects($this->once()) + $this->migration2->expects(self::once()) ->method('down') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(1, $data->calls); + Assert::assertSame(1, $data->calls); ++$data->calls; }); - $this->migration1->expects($this->once()) + $this->migration1->expects(self::once()) ->method('down') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(2, $data->calls); + Assert::assertSame(2, $data->calls); ++$data->calls; }); $this->manager->migrate($data, '0.8'); - $this->assertSame(3, $data->calls); + self::assertSame(3, $data->calls); } - public function testMigrateDownPartial() + public function testMigrateDownPartial(): void { $data = (object) array('calls' => 0); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('1.0'); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('updateVersion') ->with($data, '0.10'); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('down'); - $this->migration2->expects($this->once()) + $this->migration2->expects(self::once()) ->method('down') ->with($data) ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(0, $data->calls); + Assert::assertSame(0, $data->calls); ++$data->calls; }); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('down'); $this->manager->migrate($data, '0.10'); - $this->assertSame(1, $data->calls); + self::assertSame(1, $data->calls); } - /** - * @expectedException \Webmozart\Json\Migration\MigrationFailedException - * @expectedExceptionMessage 1.2 - */ - public function testMigrateDownFailsIfNoMigrationForSourceVersion() + public function testMigrateDownFailsIfNoMigrationForSourceVersion(): void { + $this->expectException(MigrationFailedException::class); + $this->expectExceptionMessage('1.2'); + $data = (object) array(); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('1.2'); - $this->versioner->expects($this->never()) + $this->versioner->expects(self::never()) ->method('updateVersion'); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('down'); - $this->migration2->expects($this->never()) + $this->migration2->expects(self::never()) ->method('down'); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('down'); $this->manager->migrate($data, '1.0'); } - /** - * @expectedException \Webmozart\Json\Migration\MigrationFailedException - * @expectedExceptionMessage 0.9 - */ - public function testMigrateDownFailsIfNoMigrationForTargetVersion() + public function testMigrateDownFailsIfNoMigrationForTargetVersion(): void { + $this->expectException(MigrationFailedException::class); + $this->expectExceptionMessage('0.9'); + $data = (object) array('calls' => 0); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('1.0'); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('updateVersion') ->with($data, '0.10'); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('down'); - $this->migration2->expects($this->once()) + $this->migration2->expects(self::once()) ->method('down') ->willReturnCallback(function (stdClass $data) { - PHPUnit_Framework_Assert::assertSame(0, $data->calls); + Assert::assertSame(0, $data->calls); ++$data->calls; }); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('down'); $this->manager->migrate($data, '0.9'); } - public function testMigrateDoesNothingIfAlreadyCorrectVersion() + public function testMigrateDoesNothingIfAlreadyCorrectVersion(): void { $data = (object) array(); - $this->versioner->expects($this->once()) + $this->versioner->expects(self::once()) ->method('parseVersion') ->with($data) ->willReturn('0.10'); - $this->versioner->expects($this->never()) + $this->versioner->expects(self::never()) ->method('updateVersion'); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('up'); - $this->migration2->expects($this->never()) + $this->migration2->expects(self::never()) ->method('up'); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('up'); - $this->migration1->expects($this->never()) + $this->migration1->expects(self::never()) ->method('down'); - $this->migration2->expects($this->never()) + $this->migration2->expects(self::never()) ->method('down'); - $this->migration3->expects($this->never()) + $this->migration3->expects(self::never()) ->method('down'); $this->manager->migrate($data, '0.10'); } - public function testGetKnownVersions() + public function testGetKnownVersions(): void { - $this->assertSame(array('0.8', '0.10', '1.0', '2.0'), $this->manager->getKnownVersions()); + self::assertSame(array('0.8', '0.10', '1.0', '2.0'), $this->manager->getKnownVersions()); } - public function testGetKnownVersionsWithoutMigrations() + public function testGetKnownVersionsWithoutMigrations(): void { $this->manager = new MigrationManager(array(), $this->versioner); - $this->assertSame(array(), $this->manager->getKnownVersions()); + self::assertSame(array(), $this->manager->getKnownVersions()); } /** * @param string $sourceVersion * @param string $targetVersion * - * @return PHPUnit_Framework_MockObject_MockObject|JsonMigration + * @return MockObject|JsonMigration */ - private function createMigrationMock($sourceVersion, $targetVersion) + private function createMigrationMock($sourceVersion, $targetVersion): MockObject { - $mock = $this->getMock('Webmozart\Json\Migration\JsonMigration'); + $mock = $this->createMock(JsonMigration::class); - $mock->expects($this->any()) + $mock->expects(self::any()) ->method('getSourceVersion') ->willReturn($sourceVersion); - $mock->expects($this->any()) + $mock->expects(self::any()) ->method('getTargetVersion') ->willReturn($targetVersion); diff --git a/tests/UriRetriever/LocalUriRetrieverTest.php b/tests/UriRetriever/LocalUriRetrieverTest.php index fffed97..f78e320 100644 --- a/tests/UriRetriever/LocalUriRetrieverTest.php +++ b/tests/UriRetriever/LocalUriRetrieverTest.php @@ -11,16 +11,18 @@ namespace Webmozart\Json\Tests\UriRetriever; +use PHPUnit\Framework\TestCase; use Webmozart\Json\UriRetriever\LocalUriRetriever; +use JsonSchema\Uri\Retrievers\UriRetrieverInterface; /** * @author Bernhard Schussek */ -class LocalUriRetrieverTest extends \PHPUnit_Framework_TestCase +class LocalUriRetrieverTest extends TestCase { - const GITHUB_SCHEMA_URL = 'https://raw.githubusercontent.com/webmozart/json/be0e18a01f2ef720008a91d047f16de1dc30030c/tests/Fixtures/schema.json'; + private const GITHUB_SCHEMA_URL = 'https://raw.githubusercontent.com/webmozart/json/be0e18a01f2ef720008a91d047f16de1dc30030c/tests/Fixtures/schema.json'; - const GITHUB_SCHEMA_BODY = <<<'BODY' + private const GITHUB_SCHEMA_BODY = <<<'BODY' { "id": "http://webmozart.io/fixtures/schema#", "type": "object" @@ -28,9 +30,9 @@ class LocalUriRetrieverTest extends \PHPUnit_Framework_TestCase BODY; - const GITHUB_SCHEMA_CONTENT_TYPE = 'text/plain; charset=utf-8'; + private const GITHUB_SCHEMA_CONTENT_TYPE = 'text/plain; charset=utf-8'; - public function testRetrieve() + public function testRetrieve(): void { $retriever = new LocalUriRetriever(__DIR__.'/Fixtures', array( 'http://my/schema/1.0' => 'schema-1.0.json', @@ -39,54 +41,54 @@ public function testRetrieve() $schema1Body = file_get_contents(__DIR__.'/Fixtures/schema-1.0.json'); - $this->assertSame($schema1Body, $retriever->retrieve('http://my/schema/1.0')); - $this->assertNull($retriever->getContentType()); + self::assertSame($schema1Body, $retriever->retrieve('http://my/schema/1.0')); + self::assertNull($retriever->getContentType()); - $this->assertSame(self::GITHUB_SCHEMA_BODY, $retriever->retrieve('http://my/schema/2.0')); - $this->assertSame(self::GITHUB_SCHEMA_CONTENT_TYPE, $retriever->getContentType()); + self::assertSame(self::GITHUB_SCHEMA_BODY, $retriever->retrieve('http://my/schema/2.0')); + self::assertSame(self::GITHUB_SCHEMA_CONTENT_TYPE, $retriever->getContentType()); } - public function testRetrieveLoadsUnmappedUrisFromFilesystemByDefault() + public function testRetrieveLoadsUnmappedUrisFromFilesystemByDefault(): void { $retriever = new LocalUriRetriever(); $schema1Body = file_get_contents(__DIR__.'/Fixtures/schema-1.0.json'); - $this->assertSame($schema1Body, $retriever->retrieve('file://'.__DIR__.'/Fixtures/schema-1.0.json')); - $this->assertNull($retriever->getContentType()); + self::assertSame($schema1Body, $retriever->retrieve('file://'.__DIR__.'/Fixtures/schema-1.0.json')); + self::assertNull($retriever->getContentType()); } - public function testRetrieveLoadsUnmappedUrisFromWebByDefault() + public function testRetrieveLoadsUnmappedUrisFromWebByDefault(): void { $retriever = new LocalUriRetriever(); - $this->assertSame(self::GITHUB_SCHEMA_BODY, $retriever->retrieve(self::GITHUB_SCHEMA_URL)); - $this->assertSame(self::GITHUB_SCHEMA_CONTENT_TYPE, $retriever->getContentType()); + self::assertSame(self::GITHUB_SCHEMA_BODY, $retriever->retrieve(self::GITHUB_SCHEMA_URL)); + self::assertSame(self::GITHUB_SCHEMA_CONTENT_TYPE, $retriever->getContentType()); } - public function testRetrievePassesUnmappedUrisToFallbackRetriever() + public function testRetrievePassesUnmappedUrisToFallbackRetriever(): void { - $fallbackRetriever = $this->getMock('JsonSchema\Uri\Retrievers\UriRetrieverInterface'); + $fallbackRetriever = $this->createMock(UriRetrieverInterface::class); - $fallbackRetriever->expects($this->at(0)) + $fallbackRetriever->expects(self::once()) ->method('retrieve') ->with('http://my/schema/1.0') ->willReturn('FOOBAR'); - $fallbackRetriever->expects($this->at(1)) + $fallbackRetriever->expects(self::once()) ->method('getContentType') ->willReturn('content/type'); $retriever = new LocalUriRetriever(null, array(), $fallbackRetriever); - $this->assertSame('FOOBAR', $retriever->retrieve('http://my/schema/1.0')); - $this->assertSame('content/type', $retriever->getContentType()); + self::assertSame('FOOBAR', $retriever->retrieve('http://my/schema/1.0')); + self::assertSame('content/type', $retriever->getContentType()); } - public function testGetContentTypeInitiallyReturnsNull() + public function testGetContentTypeInitiallyReturnsNull(): void { $retriever = new LocalUriRetriever(); - $this->assertNull($retriever->getContentType()); + self::assertNull($retriever->getContentType()); } } diff --git a/tests/Validation/ValidatingConverterTest.php b/tests/Validation/ValidatingConverterTest.php index bfc3d95..145a2a3 100644 --- a/tests/Validation/ValidatingConverterTest.php +++ b/tests/Validation/ValidatingConverterTest.php @@ -11,12 +11,13 @@ namespace Webmozart\Json\Tests\Validation; -use PHPUnit_Framework_Assert; -use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use JsonSchema\Exception\InvalidSchemaException; +use JsonSchema\Validator; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; +use Webmozart\Json\Conversion\ConversionFailedException; use Webmozart\Json\Conversion\JsonConverter; -use Webmozart\Json\InvalidSchemaException; -use Webmozart\Json\JsonValidator; use Webmozart\Json\Validation\ValidatingConverter; /** @@ -24,15 +25,15 @@ * * @author Bernhard Schussek */ -class ValidatingConverterTest extends PHPUnit_Framework_TestCase +class ValidatingConverterTest extends TestCase { /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonConverter + * @var MockObject|JsonConverter */ private $innerConverter; /** - * @var PHPUnit_Framework_MockObject_MockObject|JsonValidator + * @var MockObject|Validator */ private $jsonValidator; @@ -41,10 +42,10 @@ class ValidatingConverterTest extends PHPUnit_Framework_TestCase */ private $converter; - protected function setUp() + protected function setUp(): void { - $this->innerConverter = $this->getMock('Webmozart\Json\Conversion\JsonConverter'); - $this->jsonValidator = $this->getMockBuilder('Webmozart\Json\JsonValidator') + $this->innerConverter = $this->createMock(JsonConverter::class); + $this->jsonValidator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->getMock(); $this->converter = new ValidatingConverter( @@ -54,7 +55,7 @@ protected function setUp() ); } - public function testToJson() + public function testToJson(): void { $options = array('option' => 'value'); @@ -62,19 +63,19 @@ public function testToJson() 'foo' => 'bar', ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($jsonData); - $this->jsonValidator->expects($this->once()) + $this->jsonValidator->expects(self::once()) ->method('validate') ->with($jsonData, '/path/to/schema'); - $this->assertSame($jsonData, $this->converter->toJson('DATA', $options)); + self::assertSame($jsonData, $this->converter->toJson('DATA', $options)); } - public function testToJsonWithoutSchema() + public function testToJsonWithoutSchema(): void { $options = array('option' => 'value'); @@ -88,19 +89,19 @@ public function testToJsonWithoutSchema() $this->jsonValidator ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($jsonData); - $this->jsonValidator->expects($this->once()) + $this->jsonValidator->expects(self::once()) ->method('validate') ->with($jsonData, null); - $this->assertSame($jsonData, $this->converter->toJson('DATA', $options)); + self::assertSame($jsonData, $this->converter->toJson('DATA', $options)); } - public function testToJsonRunsSchemaCallable() + public function testToJsonRunsSchemaCallable(): void { $options = array('option' => 'value'); @@ -108,29 +109,29 @@ public function testToJsonRunsSchemaCallable() 'foo' => 'bar', ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($jsonData); - $this->jsonValidator->expects($this->once()) + $this->jsonValidator->expects(self::once()) ->method('validate') ->with($jsonData, '/dynamic/schema'); $this->converter = new ValidatingConverter( $this->innerConverter, function ($data) use ($jsonData) { - PHPUnit_Framework_Assert::assertSame($jsonData, $data); + Assert::assertSame($jsonData, $data); return '/dynamic/schema'; }, $this->jsonValidator ); - $this->assertSame($jsonData, $this->converter->toJson('DATA', $options)); + self::assertSame($jsonData, $this->converter->toJson('DATA', $options)); } - public function testFromJson() + public function testFromJson(): void { $options = array('option' => 'value'); @@ -138,19 +139,19 @@ public function testFromJson() 'foo' => 'bar', ); - $this->jsonValidator->expects($this->once()) + $this->jsonValidator->expects(self::once()) ->method('validate') ->with($jsonData, '/path/to/schema'); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('fromJson') ->with($jsonData, $options) ->willReturn('DATA'); - $this->assertSame('DATA', $this->converter->fromJson($jsonData, $options)); + self::assertSame('DATA', $this->converter->fromJson($jsonData, $options)); } - public function testFromJsonWithoutSchema() + public function testFromJsonWithoutSchema(): void { $options = array('option' => 'value'); @@ -164,19 +165,19 @@ public function testFromJsonWithoutSchema() $this->jsonValidator ); - $this->jsonValidator->expects($this->once()) + $this->jsonValidator->expects(self::once()) ->method('validate') ->with($jsonData, null); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('fromJson') ->with($jsonData, $options) ->willReturn('DATA'); - $this->assertSame('DATA', $this->converter->fromJson($jsonData, $options)); + self::assertSame('DATA', $this->converter->fromJson($jsonData, $options)); } - public function testFromJsonRunsSchemaCallable() + public function testFromJsonRunsSchemaCallable(): void { $options = array('option' => 'value'); @@ -184,11 +185,11 @@ public function testFromJsonRunsSchemaCallable() 'foo' => 'bar', ); - $this->jsonValidator->expects($this->once()) + $this->jsonValidator->expects(self::once()) ->method('validate') ->with($jsonData, '/dynamic/schema'); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('fromJson') ->with($jsonData, $options) ->willReturn('DATA'); @@ -196,60 +197,38 @@ public function testFromJsonRunsSchemaCallable() $this->converter = new ValidatingConverter( $this->innerConverter, function ($data) use ($jsonData) { - PHPUnit_Framework_Assert::assertSame($jsonData, $data); + Assert::assertSame($jsonData, $data); return '/dynamic/schema'; }, $this->jsonValidator ); - $this->assertSame('DATA', $this->converter->fromJson($jsonData, $options)); + self::assertSame('DATA', $this->converter->fromJson($jsonData, $options)); } - /** - * @expectedException \Webmozart\Json\Conversion\ConversionFailedException - */ - public function testConvertSchemaExceptionToConversionException() + public function testConvertValidationErrorsToConversionException(): void { - $options = array('option' => 'value'); - - $jsonData = (object) array( - 'foo' => 'bar', - ); - - $this->innerConverter->expects($this->once()) - ->method('toJson') - ->with('DATA', $options) - ->willReturn($jsonData); + $this->expectException(ConversionFailedException::class); - $this->jsonValidator->expects($this->once()) - ->method('validate') - ->willThrowException(new InvalidSchemaException()); - - $this->converter->toJson('DATA', $options); - } - - /** - * @expectedException \Webmozart\Json\Conversion\ConversionFailedException - */ - public function testConvertValidationErrorsToConversionException() - { $options = array('option' => 'value'); $jsonData = (object) array( 'foo' => 'bar', ); - $this->innerConverter->expects($this->once()) + $this->innerConverter->expects(self::once()) ->method('toJson') ->with('DATA', $options) ->willReturn($jsonData); - $this->jsonValidator->expects($this->once()) - ->method('validate') - ->willReturn(array( + $this->jsonValidator->expects(self::once()) + ->method('validate'); + + $this->jsonValidator->expects(self::once()) + ->method('getErrors')->willReturn(array( 'First error', - 'Second error', + ['Second error'], )); $this->converter->toJson('DATA', $options); diff --git a/tests/Versioning/SchemaUriVersionerTest.php b/tests/Versioning/SchemaUriVersionerTest.php index bb4fd17..a71ef63 100644 --- a/tests/Versioning/SchemaUriVersionerTest.php +++ b/tests/Versioning/SchemaUriVersionerTest.php @@ -11,7 +11,9 @@ namespace Webmozart\Json\Tests\Versioning; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; +use Webmozart\Json\Versioning\CannotParseVersionException; +use Webmozart\Json\Versioning\CannotUpdateVersionException; use Webmozart\Json\Versioning\SchemaUriVersioner; /** @@ -19,93 +21,89 @@ * * @author Bernhard Schussek */ -class SchemaUriVersionerTest extends PHPUnit_Framework_TestCase +class SchemaUriVersionerTest extends TestCase { /** * @var SchemaUriVersioner */ private $versioner; - protected function setUp() + protected function setUp(): void { $this->versioner = new SchemaUriVersioner(); } - public function testParseVersion() + public function testParseVersion(): void { $data = (object) array('$schema' => 'http://example.com/schemas/1.0/schema'); - $this->assertSame('1.0', $this->versioner->parseVersion($data)); + self::assertSame('1.0', $this->versioner->parseVersion($data)); } - /** - * @expectedException \Webmozart\Json\Versioning\CannotParseVersionException - */ - public function testParseVersionFailsIfNotFound() + public function testParseVersionFailsIfNotFound(): void { + $this->expectException(CannotParseVersionException::class); + $data = (object) array('$schema' => 'http://example.com/schemas/1.0-schema'); $this->versioner->parseVersion($data); } - public function testParseVersionWithCustomPattern() + public function testParseVersionWithCustomPattern(): void { $this->versioner = new SchemaUriVersioner('~(?<=/)\d+\.\d+(?=-)~'); $data = (object) array('$schema' => 'http://example.com/schemas/1.0-schema'); - $this->assertSame('1.0', $this->versioner->parseVersion($data)); + self::assertSame('1.0', $this->versioner->parseVersion($data)); } - /** - * @expectedException \Webmozart\Json\Versioning\CannotParseVersionException - */ - public function testParseVersionFailsIfNoSchemaField() + public function testParseVersionFailsIfNoSchemaField(): void { + $this->expectException(CannotParseVersionException::class); + $data = (object) array('foo' => 'bar'); $this->versioner->parseVersion($data); } - public function testUpdateVersion() + public function testUpdateVersion(): void { $data = (object) array('$schema' => 'http://example.com/schemas/1.0/schema'); $this->versioner->updateVersion($data, '2.0'); - $this->assertSame('http://example.com/schemas/2.0/schema', $data->{'$schema'}); + self::assertSame('http://example.com/schemas/2.0/schema', $data->{'$schema'}); } - public function testUpdateVersionIgnoresCurrentVersion() + public function testUpdateVersionIgnoresCurrentVersion(): void { $data = (object) array('$schema' => 'http://example.com/schemas/1.0/schema'); $this->versioner->updateVersion($data, '1.0'); - $this->assertSame('http://example.com/schemas/1.0/schema', $data->{'$schema'}); + self::assertSame('http://example.com/schemas/1.0/schema', $data->{'$schema'}); } - /** - * @expectedException \Webmozart\Json\Versioning\CannotUpdateVersionException - */ - public function testUpdateVersionFailsIfNotFound() + public function testUpdateVersionFailsIfNotFound(): void { + $this->expectException(CannotUpdateVersionException::class); + $data = (object) array('$schema' => 'http://example.com/schemas/1.0-schema'); $this->versioner->updateVersion($data, '2.0'); } - /** - * @expectedException \Webmozart\Json\Versioning\CannotUpdateVersionException - */ - public function testUpdateVersionFailsIfFoundMultipleTimes() + public function testUpdateVersionFailsIfFoundMultipleTimes(): void { + $this->expectException(CannotUpdateVersionException::class); + $data = (object) array('$schema' => 'http://example.com/1.0/schemas/1.0/schema'); $this->versioner->updateVersion($data, '2.0'); } - public function testUpdateVersionCustomPattern() + public function testUpdateVersionCustomPattern(): void { $this->versioner = new SchemaUriVersioner('~(?<=/)\d+\.\d+(?=-)~'); @@ -113,14 +111,13 @@ public function testUpdateVersionCustomPattern() $this->versioner->updateVersion($data, '2.0'); - $this->assertSame('http://example.com/schemas/2.0-schema', $data->{'$schema'}); + self::assertSame('http://example.com/schemas/2.0-schema', $data->{'$schema'}); } - /** - * @expectedException \Webmozart\Json\Versioning\CannotUpdateVersionException - */ - public function testUpdateVersionFailsIfNoSchemaField() + public function testUpdateVersionFailsIfNoSchemaField(): void { + $this->expectException(CannotUpdateVersionException::class); + $data = (object) array('foo' => 'bar'); $this->versioner->updateVersion($data, '2.0'); diff --git a/tests/Versioning/VersionFieldVersionerTest.php b/tests/Versioning/VersionFieldVersionerTest.php index 159f20d..47e416b 100644 --- a/tests/Versioning/VersionFieldVersionerTest.php +++ b/tests/Versioning/VersionFieldVersionerTest.php @@ -11,7 +11,8 @@ namespace Webmozart\Json\Tests\Versioning; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; +use Webmozart\Json\Versioning\CannotParseVersionException; use Webmozart\Json\Versioning\VersionFieldVersioner; /** @@ -19,54 +20,53 @@ * * @author Bernhard Schussek */ -class VersionFieldVersionerTest extends PHPUnit_Framework_TestCase +class VersionFieldVersionerTest extends TestCase { /** * @var VersionFieldVersioner */ private $versioner; - protected function setUp() + protected function setUp(): void { $this->versioner = new VersionFieldVersioner(); } - public function testParseVersion() + public function testParseVersion(): void { $data = (object) array('version' => '1.0'); - $this->assertSame('1.0', $this->versioner->parseVersion($data)); + self::assertSame('1.0', $this->versioner->parseVersion($data)); } - public function testParseVersionCustomFieldName() + public function testParseVersionCustomFieldName(): void { $this->versioner = new VersionFieldVersioner('foo'); $data = (object) array('foo' => '1.0'); - $this->assertSame('1.0', $this->versioner->parseVersion($data)); + self::assertSame('1.0', $this->versioner->parseVersion($data)); } - /** - * @expectedException \Webmozart\Json\Versioning\CannotParseVersionException - */ - public function testParseVersionFailsIfNotFound() + public function testParseVersionFailsIfNotFound(): void { + $this->expectException(CannotParseVersionException::class); + $data = (object) array('foo' => 'bar'); $this->versioner->parseVersion($data); } - public function testUpdateVersion() + public function testUpdateVersion(): void { $data = (object) array('version' => '1.0'); $this->versioner->updateVersion($data, '2.0'); - $this->assertSame('2.0', $data->version); + self::assertSame('2.0', $data->version); } - public function testUpdateVersionCustomFieldName() + public function testUpdateVersionCustomFieldName(): void { $this->versioner = new VersionFieldVersioner('foo'); @@ -74,15 +74,15 @@ public function testUpdateVersionCustomFieldName() $this->versioner->updateVersion($data, '2.0'); - $this->assertSame('2.0', $data->foo); + self::assertSame('2.0', $data->foo); } - public function testUpdateVersionCreatesFieldIfNotFound() + public function testUpdateVersionCreatesFieldIfNotFound(): void { $data = (object) array('foo' => 'bar'); $this->versioner->updateVersion($data, '2.0'); - $this->assertSame('2.0', $data->version); + self::assertSame('2.0', $data->version); } }