Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/Type/EnumType.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use EventEngine\JsonSchema\AnnotatedType;
use EventEngine\JsonSchema\JsonSchema;
use EventEngine\JsonSchema\Type;

class EnumType implements AnnotatedType
{
Expand Down Expand Up @@ -41,4 +42,16 @@ public function toArray(): array
'enum' => $this->entries,
], $this->annotations());
}

public function asNullable(): Type
{
$cp = clone $this;

$this->assertTypeCanBeConvertedToNullableType($cp);

$cp->type = [$cp->type, JsonSchema::TYPE_NULL];
$cp->entries[] = null;

return $cp;
}
}
21 changes: 15 additions & 6 deletions src/Type/NullableType.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,25 @@ public function asNullable(): Type
{
$cp = clone $this;

$this->assertTypeCanBeConvertedToNullableType($cp);

$cp->type = [$cp->type, JsonSchema::TYPE_NULL];

return $cp;
}

protected function assertTypeCanBeConvertedToNullableType(Type $cp): void
{
if (! isset($cp->type)) {
throw new \RuntimeException('Type cannot be converted to nullable type. No json schema type set for ' . \get_class($this));
throw new \RuntimeException(
'Type cannot be converted to nullable type. No json schema type set for ' . \get_class($this)
);
}

if (! \is_string($cp->type)) {
throw new \RuntimeException('Type cannot be converted to nullable type. JSON schema type is not a string');
throw new \RuntimeException(
'Type cannot be converted to nullable type. JSON schema type is not a string'
);
}

$cp->type = [$cp->type, JsonSchema::TYPE_NULL];

return $cp;
}
}
50 changes: 50 additions & 0 deletions tests/Type/EnumTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php
/**
* This file is part of the event-engine/php-json-schema.
* (c) 2017-2019 prooph software GmbH <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace EventEngineTest\JsonSchema\Type;

use EventEngine\JsonSchema\Type\EnumType;
use EventEngineTest\JsonSchema\BasicTestCase;

final class EnumTypeTest extends BasicTestCase
{
/**
* @test
*/
public function it_creates_enum_type()
{
$enumType = new EnumType('a', 'b');

$this->assertEquals(
[
'type' => 'string',
'enum' => ['a', 'b'],
],
$enumType->toArray()
);
}

/**
* @test
*/
public function it_creates_nullable_enum_type()
{
$enumType = (new EnumType('a', 'b'))->asNullable();

$this->assertEquals(
[
'type' => ['string', 'null'],
'enum' => ['a', 'b', null]
],
$enumType->toArray()
);
}
}