Skip to content

Commit 9fdeca8

Browse files
feat: 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 9fdeca8

2 files changed

Lines changed: 23 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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@ public function testObjectsAreStrings(): void
5454
$this->assertSame('Object Sentry\Tests\Serializer\SerializerTestObject', $result);
5555
}
5656

57+
/**
58+
* @requires PHP >= 8.1
59+
*/
60+
public function testEnumsAreNames(): void
61+
{
62+
$serializer = $this->createSerializer();
63+
$input = SerializerTestEnum::CASE_NAME;
64+
$result = $this->invokeSerialization($serializer, $input);
65+
66+
$this->assertSame('Enum Sentry\Tests\Serializer\SerializerTestEnum::CASE_NAME', $result);
67+
}
68+
5769
public static function objectsWithIdPropertyDataProvider(): array
5870
{
5971
return [
@@ -651,6 +663,11 @@ public static function testy(): void
651663
}
652664
}
653665

666+
enum SerializerTestEnum
667+
{
668+
case CASE_NAME;
669+
}
670+
654671
class SerializerTestObjectWithIdProperty extends SerializerTestObject
655672
{
656673
public $id = 'bar';

0 commit comments

Comments
 (0)