Skip to content

Commit 6ac7a5a

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 6ac7a5a

3 files changed

Lines changed: 28 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: 12 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 [
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Sentry\Tests\Serializer;
6+
7+
enum SerializerTestEnum
8+
{
9+
case CASE_NAME;
10+
}

0 commit comments

Comments
 (0)