diff --git a/src/Schema/Exception/TypeMismatch.php b/src/Schema/Exception/TypeMismatch.php index 8435244b..880f3719 100644 --- a/src/Schema/Exception/TypeMismatch.php +++ b/src/Schema/Exception/TypeMismatch.php @@ -4,8 +4,11 @@ namespace League\OpenAPIValidation\Schema\Exception; +use League\OpenAPIValidation\Foundation\ArrayHelper; + use function gettype; use function implode; +use function is_array; use function sprintf; // Validation for 'type' keyword failed against a given data @@ -19,7 +22,8 @@ class TypeMismatch extends KeywordMismatch */ public static function becauseTypeDoesNotMatch(array $expected, $value): self { - $exception = new self(sprintf("Value expected to be '%s', but '%s' given.", implode(', ', $expected), gettype($value))); + $givenType = is_array($value) && ArrayHelper::isAssoc($value) ? 'object' : gettype($value); + $exception = new self(sprintf("Value expected to be '%s', but '%s' given.", implode(', ', $expected), $givenType)); $exception->data = $value; $exception->keyword = 'type'; diff --git a/tests/Schema/Keywords/TypeTest.php b/tests/Schema/Keywords/TypeTest.php index ec149005..4dc017cc 100644 --- a/tests/Schema/Keywords/TypeTest.php +++ b/tests/Schema/Keywords/TypeTest.php @@ -4,11 +4,15 @@ namespace League\OpenAPIValidation\Tests\Schema\Keywords; +use League\OpenAPIValidation\Foundation\ArrayHelper; use League\OpenAPIValidation\Schema\Exception\TypeMismatch; use League\OpenAPIValidation\Schema\SchemaValidator; use League\OpenAPIValidation\Tests\Schema\SchemaValidatorTest; use stdClass; +use function gettype; +use function is_array; + final class TypeTest extends SchemaValidatorTest { /** @@ -66,6 +70,15 @@ public function testItValidatesTypeRed(string $type, $invalidValue): void $schema = $this->loadRawSchema($spec); $this->expectException(TypeMismatch::class); + switch ($type) { + case 'array': + $expectedMsg = is_array($invalidValue) && ArrayHelper::isAssoc($invalidValue) + ? "Value expected to be 'array', but 'object' given." + : "Value expected to be 'array', but '" . gettype($invalidValue) . "' given."; + $this->expectExceptionMessage($expectedMsg); + break; + } + (new SchemaValidator())->validate($invalidValue, $schema); } @@ -78,6 +91,8 @@ public function invalidDataProvider(): array ['string', 12], ['object', 'not object'], ['array', ['a' => 1, 'b' => 2]], // this is not a plain array (a-la JSON) + ['array', [0 => 'a', 2 => 'b']], // this is not an array per JSON spec + ['array', 'not array'], ['boolean', [1, 2]], ['boolean', 'True'], ['boolean', ''],