Skip to content
Open
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
18 changes: 13 additions & 5 deletions src/JsonMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -296,12 +296,20 @@ public function map($json, $object)
} else if (is_array($jvalue) && $this->hasVariadicArrayType($accessor)) {
$array = array();
$subtype = $type;
} else {
if (is_a($type, 'ArrayAccess', true)
&& is_a($type, 'Traversable', true)
) {
$array = $this->createInstance($type, false, $jvalue);
} else if (is_a($type, 'ArrayAccess', true)
&& is_a($type, 'Traversable', true)
) {
$array = $this->createInstance($type, false, $jvalue);
} else if (PHP_VERSION_ID >= 80100 && enum_exists($type)) {
$evalue = $type::tryFrom($jvalue);
if ($evalue === null) {
throw new JsonMapper_Exception(
'Enum value "' . $jvalue . '" does not belong to '
. $type . ' enumerator class'
);
}
$this->setProperty($object, $accessor, $evalue);
continue;
}

if ($array !== null) {
Expand Down
41 changes: 41 additions & 0 deletions tests/Enums_PHP81_Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,45 @@ public function testEnumMapping()
$this->assertSame(\Enums\StringBackedEnum::FOO, $sn->stringBackedEnum);
$this->assertSame(\Enums\IntBackedEnum::BAR, $sn->intBackedEnum);
}

/**
* Test that string values are correctly mapped to backed enum properties.
*/
public function testBackedEnumPropertyIsMappedFromString(): void
{
$json = (object) [
'stringBackedEnum' => 'foo',
'intBackedEnum' => 2,
];

$mapper = new \JsonMapper();
$target = new \Enums\ObjectWithEnum();

$mapped = $mapper->map($json, $target);

$this->assertSame(
\Enums\StringBackedEnum::FOO,
$mapped->stringBackedEnum,
'Expected JSON scalar to be converted to the corresponding backed enum case'
);
}

/**
* Test that mapping invalid string values to backed enum properties throws an exception.
*/
public function testBackedEnumPropertyWithInvalidStringThrowsJsonMapperException(): void
{
$json = (object) [
'stringBackedEnum' => 'not-a-valid-enum-value',
'intBackedEnum' => 'not-a-valid-enum-value',
];

$mapper = new \JsonMapper();
$target = new \Enums\ObjectWithEnum();

$this->expectException(\JsonMapper_Exception::class);
$this->expectExceptionMessage('Enum value "not-a-valid-enum-value" does not belong to');

$mapper->map($json, $target);
}
}