Crell / Serde

Robust Serde (serialization/deserialization) library for PHP 8.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ability to flatten single property objects

agustingomes opened this issue · comments

Detailed description

Ability to flatten objects with single properties automatically

Context

When working on a bounded context, it may be desirable to create an identity representation so it can have specific behavior to the domain. This can be useful for instance, when deserializing JSON payloads from en event sourced system.

Consider the following payload:

{
  "id": "identity",
  "name": "Testing Purposes"
}

and considering the following object representation:

final class Identity
{
    public function __construct(
        public readonly string $value,
    ) {
    }
}

final class FlattenSingleProperty
{
    public function __construct(
        public readonly Identity $id,
        public readonly string $name,
    ) {
    }
}

It would be ideal to successfully deserialize the object representation without having to specify the value property in the JSON payload.

How can it benefit other users?

It may be beneficial for other users for the same reason as my current use case: to avoid specifying a single property for domain objects.

Possible implementation

I went ahead and added a test case which hopefully conveys the idea and the expectation better. The test case is currently failing as I'm not sure yet in which part of the project to do the check for an object having a single property.

Branch with the test

Your environment

PHP 8.2

This is closely related to #42, and a fix would probably need to address both simultaneously.

I will say that I don't think auto-flattening single-property objects is wise. There's plenty of reasons you wouldn't want to do that. But making it easier to mark a value object as flattenable I'm open to, if we can determine a good way to do so.

That is indeed closely related. I'll close this issue in favor of the #42