Skip to content

Add/require hard-coded key/value(s) #79

@Nadyita

Description

@Nadyita

Been enjoying your package for a very long time now, and gradually replacing some custom components I wrote with this generic one.
A very common use case that I have is packages from protocols, where each package has a fixed {"type": <value>} attribute that determines the type of package. Deserializing is not an issue, but because that type is not a property in my data object (it's a constant after all), and the data objects tend to have public accessor functions, I'm forced to set serialization of public methods tofalse.
What I would love would be a way to annotate a class that it should always add a key/value pair when serializing the object, but also requiring this key/value pair when hydrating. Something like

#[FixedDefinition(key: 'type', value: 'get-users')]
class GetUsersCommand {
    /** @param list<string> $users */
    public function __construct(
        public readonly array $users
    ) {
    }
}

This should always add {"type": "get-users"} when serializing, and also require this key/value-pair when hydrating. So far, I'm not seeing an easy way to do this with the given codebase. Would you be open to a PR implementing this, or is this too much a niche thing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions