diff --git a/src/spec/Schema.php b/src/spec/Schema.php index 59eb425c..b8c0709e 100644 --- a/src/spec/Schema.php +++ b/src/spec/Schema.php @@ -124,6 +124,10 @@ protected function attributeDefaults(): array 'allOf' => null, 'oneOf' => null, 'anyOf' => null, + // nullable is only relevant, when a type is specified + // return null as default when there is no type + // return false as default when there is a type + 'nullable' => $this->hasProperty('type') ? false : null, ]; } diff --git a/tests/spec/SchemaTest.php b/tests/spec/SchemaTest.php index be53dd9b..0e19f74e 100644 --- a/tests/spec/SchemaTest.php +++ b/tests/spec/SchemaTest.php @@ -43,6 +43,29 @@ public function testRead() $this->assertFalse($schema->deprecated); } + public function testNullable() + { + /** @var $schema Schema */ + $schema = Reader::readFromJson('{"type": "string"}', Schema::class); + $this->assertEquals(Type::STRING, $schema->type); + $this->assertFalse($schema->nullable); + + /** @var $schema Schema */ + $schema = Reader::readFromJson('{"type": "string", "nullable": false}', Schema::class); + $this->assertEquals(Type::STRING, $schema->type); + $this->assertFalse($schema->nullable); + + /** @var $schema Schema */ + $schema = Reader::readFromJson('{"type": "string", "nullable": true}', Schema::class); + $this->assertEquals(Type::STRING, $schema->type); + $this->assertTrue($schema->nullable); + + // nullable is undefined if no type is given + $schema = Reader::readFromJson('{"oneOf": [{"type": "string"}, {"type": "integer"}]}', Schema::class); + $this->assertNull($schema->type); + $this->assertNull($schema->nullable); + } + public function testReadObject() { /** @var $schema Schema */