Skip to content

Allow class_serializers option to allow generic serializers without specific type, handling any object #889

@JanMikes

Description

@JanMikes

Hi!

I like concept of class serializes, but i have a bit specific use case:

I have 100+ classes like this:

final class OrderId
{
    use EntityId;
}

And would love to be able to serialize them. They have no common parent or either interface.

At first my idea was something like:

final class GenericSentrySerializer
{
    /**
     * @param object $object
     */
    public function __invoke($object): ?array
    {
        if (method_exists($object, 'id')) {
            return [
                'id' => (string) $object->id(),
            ];
        }

        if (in_array(EntityId::class, \Safe\class_uses($object), true)) {
            return [
                'id' => (string) $object,
            ];
        }

        return null;
    }
}

But this does not work, since i have to pass into Options object array of $type => $serializer (AbstractSerializer::resolveClassSerializers():

foreach ($this->options->getClassSerializers() as $type => $serializer) {
            if ($object instanceof $type) { // <<<<<---- here it will fail
                $serializers[] = $serializer;
            }
        }

Do you have any ideas how to overcome this limitation?

I could imagine having option generic_class_serializers or universal_class_serializers :-)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions