Skip to content

Fix for readonly properties that declared in parent #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 14, 2024
Merged
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
4 changes: 4 additions & 0 deletions src/Serializers/Native.php
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,10 @@ protected function mapByReference(&$data)
continue;
}

if (PHP_VERSION >= 8.1 && $property->isReadOnly() && $property->class !== $reflection->name) {
continue;
}

$value = $property->getValue($instance);

if (is_array($value) || is_object($value)) {
Expand Down
31 changes: 31 additions & 0 deletions tests/SerializerPhp81Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,28 @@ enum SerializerScopedBackedEnum: string {
);
})->with('serializers');

test('readonly properties declared in parent', function () {
$childWithDefaultValue = new SerializerPhp81Child();

$f = static function () use ($childWithDefaultValue) {
return $childWithDefaultValue;
};

$f = s($f);

expect($f()->property)->toBe(1);

$child = new SerializerPhp81Child(100);

$f = static function () use ($child) {
return $child;
};

$f = s($f);

expect($f()->property)->toBe(100);
})->with('serializers');

test('first-class callable with closures', function () {
$f = function ($value) {
return $value;
Expand Down Expand Up @@ -584,6 +606,15 @@ enum SerializerScopedBackedEnum: string {
interface SerializerPhp81HasId {}
interface SerializerPhp81HasName {}

class SerializerPhp81Child extends SerializerPhp81Parent {}

class SerializerPhp81Parent
{
public function __construct(
public readonly int $property = 1,
) {}
}

class SerializerPhp81Service implements SerializerPhp81HasId, SerializerPhp81HasName
{
final public const X = 'foo';
Expand Down