From 1c4a4faac6ba7ef6363943a0aa4a487d64b5afe9 Mon Sep 17 00:00:00 2001 From: kafkiansky Date: Tue, 17 Nov 2026 08:50:17 +0300 Subject: [PATCH] fix: do not mutate user maps of messages when encoding --- .../Visitor/ToProtobufValueTypeVisitor.php | 7 ++- tests/MapEncodingTest.php | 61 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 tests/MapEncodingTest.php diff --git a/src/Reflection/Internal/Visitor/ToProtobufValueTypeVisitor.php b/src/Reflection/Internal/Visitor/ToProtobufValueTypeVisitor.php index 6c668c7..47ff17a 100644 --- a/src/Reflection/Internal/Visitor/ToProtobufValueTypeVisitor.php +++ b/src/Reflection/Internal/Visitor/ToProtobufValueTypeVisitor.php @@ -185,12 +185,15 @@ public function map(MapT $type): \Closure if ($type->valueT->accept(new IsObjectType())) { $mapper = $type->valueT->accept(new ToProtobufMessageTypeVisitor($this->reflector)); + // The user's map must stay untouched: build a new one with the mapped values. $mapValue = static function (Protobuf\Map $map) use ($mapper): Protobuf\Map { + $mapped = new Protobuf\Map(); + foreach ($map as $key => $val) { - $map[$key] = $mapper($val); + $mapped[$key] = $mapper($val); } - return $map; + return $mapped; }; } diff --git a/tests/MapEncodingTest.php b/tests/MapEncodingTest.php new file mode 100644 index 0000000..db6d4ae --- /dev/null +++ b/tests/MapEncodingTest.php @@ -0,0 +1,61 @@ + $inner])); + + $first = $encoder->encode($message); + $second = $encoder->encode($message); + + self::assertSame('0a070a016112020805', bin2hex($first)); + self::assertSame($first, $second); + self::assertSame($inner, $message->values['a']); + } + + public function testMapOfObjectsRoundTrips(): void + { + $bytes = Encoder\Builder::buildDefault()->encode(new MapEncodingTestWithMap(Map::fromArray([ + 'a' => new MapEncodingTestInner(5), + 'b' => new MapEncodingTestInner(7), + ]))); + + $decoded = Decoder\Builder::buildDefault()->decode($bytes, MapEncodingTestWithMap::class); + + self::assertEquals(new MapEncodingTestInner(5), $decoded->values['a']); + self::assertEquals(new MapEncodingTestInner(7), $decoded->values['b']); + self::assertCount(2, $decoded->values); + } +} + +final readonly class MapEncodingTestInner +{ + public function __construct( + #[Reflection\Field(1, Reflection\Int32T::T)] + public int $value = 0, + ) {} +} + +final readonly class MapEncodingTestWithMap +{ + /** + * @param Map $values + */ + public function __construct( + #[Reflection\Field(1, new Reflection\MapT(Reflection\StringT::T, new Reflection\ObjectT(MapEncodingTestInner::class)))] + public Map $values = new Map(), + ) {} +}