Skip to content

Commit d3d7b35

Browse files
Serialize Enum variants with the variant name
With enum types it's almost always useful to know exactly which variant is being logged. But the current serializers don't differentiate between enums and objects. This changes the serializers to add the variant name of the enum that is being serialized.
1 parent 5fc99eb commit d3d7b35

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

src/Serializer/AbstractSerializer.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,12 @@ protected function serializeValue($value)
241241
return $value;
242242
}
243243

244+
if ($value instanceof \UnitEnum) {
245+
$reflection = new \ReflectionObject($value);
246+
247+
return 'Enum ' . $reflection->getName() . '::' . $value->name;
248+
}
249+
244250
if (\is_object($value)) {
245251
$reflection = new \ReflectionObject($value);
246252

tests/Serializer/AbstractSerializerTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ public function testObjectsAreStrings(): void
5454
$this->assertSame('Object Sentry\Tests\Serializer\SerializerTestObject', $result);
5555
}
5656

57+
public function testEnumsAreNames(): void
58+
{
59+
$serializer = $this->createSerializer();
60+
$input = SerializerTestEnum::CASE_NAME;
61+
$result = $this->invokeSerialization($serializer, $input);
62+
63+
$this->assertSame('Enum Sentry\Tests\Serializer\SerializerTestEnum::CASE_NAME', $result);
64+
}
65+
5766
public static function objectsWithIdPropertyDataProvider(): array
5867
{
5968
return [
@@ -651,6 +660,11 @@ public static function testy(): void
651660
}
652661
}
653662

663+
enum SerializerTestEnum
664+
{
665+
case CASE_NAME;
666+
}
667+
654668
class SerializerTestObjectWithIdProperty extends SerializerTestObject
655669
{
656670
public $id = 'bar';

0 commit comments

Comments
 (0)