-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Serializer] Support readonly
classes or classes that use readonly for constructor property promotion
#49808
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
Comments
I'm on PHP 8.1 and I write commands that are (de)serialized with |
Thanks for your reply 😊 |
I've just created a symfony/skeleton:^5.4 project, added symfony/serializer and symfony/property-access and successfully (de)serialized class with readonly properties. See code<?php
namespace App;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Serializer\SerializerInterface;
#[AsCommand(name: 'my-command')]
class MyCommand extends Command
{
function __construct(
private SerializerInterface $serializer
){
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$a = new A('a', 1);
$serialized = $this->serializer->serialize($a, 'json');
dump($serialized);
$deserialized = $this->serializer->deserialize($serialized, A::class, 'json');
dump($deserialized);
return 1;
}
}
class A {
function __construct(
public readonly string $field1,
public readonly int $field2,
) {}
} Output: ^ "{"field1":"a","field2":1}"
^ App\A^ {#155
+field1: "a"
+field2: 1
} |
I am going to close here for now due to the lack of feedback. Please let us know when you have more information and we can consider to reopen. |
For reference, I also encountered a different error using read-only CPP properties that was caused by a seemingly unrelated name converter bug: #50042 As the ObjectNormalizer falls back to properties when it can't correctly handle a constructor, such bugs went unnoticed until now. |
Description
The Serializer is perfectly capable of deserializing the following object without configuration:
But as soon as you make the class
readonly
(PHP 8.2 feature) or make the constructor propertiesreadonly
(PHP 8.1) you'll get an error:Example
No response
The text was updated successfully, but these errors were encountered: