Skip to content
New issue

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

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

Already on GitHub? # to your account

Undefined property error when mapping from stdClass to class with nullable properties #181

Closed
MrMeshok opened this issue Sep 2, 2024 · 0 comments · Fixed by #184
Closed

Comments

@MrMeshok
Copy link
Contributor

MrMeshok commented Sep 2, 2024

readonly class Response
{
    public function __construct(
        public int $ResponseCode,
        public ?string $ResponseDescription = null,
    ) {}
}

$data = new \stdClass();
$data->ResponseCode = 0;

$dto = $autoMapper->map($data, Response::class);

With this code, mapper will generate code like this:

$value_1 = null;
if (null !== $value->ResponseDescription) {
    $value_1 = $value->ResponseDescription;
}
$constructarg_1 = $value_1 ?? NULL;

And we will get an undefined property error because ResponseDescription is not guaranteed to exist in the source.
But if data is an array, the generated code looks like this:

$value_1 = null;
if (isset($value['ResponseDescription'])) {
    $value_1 = $value['ResponseDescription'];
}
$constructarg_1 = $value_1 ?? NULL;

So when source is an object and target property is nullable or has default value we need to do this:

$constructarg_1 = $value->ResponseDescription ?? NULL;

Also, array code can be rewritten too

$constructarg_1 = $value['ResponseDescription'] ?? NULL;

And I can work on implementation myself, I already did some testing

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
1 participant