docs icon indicating copy to clipboard operation
docs copied to clipboard

Changing the Serialization Context Dynamically

Open Oipnet opened this issue 3 years ago • 1 comments

This part of the documentation does not seem to be up to date.

When we retrieve the context there is no more 'groups' key. We can retrieve the normalization group of our operation in the 'operation' key but there is no setter on the Operation class to modify dynamically the normalization group.

Is it still possible in Api-p 3 ? Should this part of the documentation be removed?

Oipnet avatar Oct 11 '22 12:10 Oipnet

for anyone who might encounter this issue, in my case I did the following, hope it helps:

public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
{
    $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
    $resourceClass = $context['resource_class'] ?? null;

    if (
        MyClass::class === $resourceClass
        && array_key_exists('operation', $context)
        && $context['operation'] instanceof Patch
        && false === $normalization
    ) {
        $denormalizationContext['groups'] = ['special_update_group'];
        $context['operation'] = $context['operation']->withDenormalizationContext($denormalizationContext);
    }

    return $context;
}

aburian avatar Mar 02 '23 09:03 aburian