Skip to content
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

Force serialize nullable properties using a handler #938

Open
ozahorulia opened this issue Oct 14, 2023 · 0 comments
Open

Force serialize nullable properties using a handler #938

ozahorulia opened this issue Oct 14, 2023 · 0 comments

Comments

@ozahorulia
Copy link

ozahorulia commented Oct 14, 2023

Q A
Bug report? no
Feature request? yes
BC Break report? no
RFC? no

I've got a nullable property, and I want to serialize it to a specific value even if it's null. It probably can be done by triggering a handler with the specified type even if the value is null

App\Entity\Item:
    exclusion_policy: ALL
        category:
            type: App\Entity\Category

App\Entity\Category:
    exclusion_policy: ALL
        name: ~
        slug: ~
class CategoryHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods(): array
    {
        return [
            [
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => Category::class,
                'method' => 'toJson',
            ],
        ];
    }

    public function toJson(JsonSerializationVisitor $visitor, ?Category $category, array $type, Context $context): string
    {
        if ($category === null) {
            return ['name' => 'UNKNOWN', 'slug' => null];
        } else {
            // IF IT'S NOT NULL, USE DEFAULT SERIALIZATION FLOW
        }
    }
}
$context = SerializationContext::create();
$context->setSerializeNull(true);

return $this->serializer->serialize(new Item(category: null), 'json', $context);

Right now, output is always:

{
    "category": null,
}

And I want it to be:

{
    "category": {
        "name": "Name",
        "slug": "slug"
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant