Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom normalizer and normalization support

I want to (de)normalise my data following the "example" found in the doc here, but the supportNormalization method of AbstractItemNormalizer always returns false.

As the doc is completely unhelpful about what should be done, and how, could anyone help me here? I cannot find a working example anywhere.

like image 577
Shautieh Avatar asked Sep 13 '26 08:09

Shautieh


1 Answers

First we can see from the definition of the method:

/**
 * Checks whether the given class is supported for normalization by this normalizer.
 *
 * @param mixed  $data   Data to normalize
 * @param string $format The format being (de-)serialized from or into
 *
 * @return bool
 */
public function supportsNormalization($data, $format = null);

that this method returns false when your $data normalization is not supported by this normalizer. And only when this method returns true your normalize method will be called.

First parameter that supportNormalization receives is format e.g. json, jsonapi, jsonhal, etc.

So if you in your api_platform.yaml config have something like:

api_platform:
    formats:
         jsonld:   ['application/ld+json']

but you in your services.yaml register service:

services:
    'App\Serializer\CustomItemNormalizer':
        arguments: [ '@api_platform.serializer.normalizer.item' ]

supportNormalization will always return false, because your inject/decorate normalizer does not support jsonld, and you need to have:

services:
    'App\Serializer\CustomItemNormalizer':
        arguments: [ 'api_platform.jsonld.normalizer.item' ]

Here you have a list of list of available serializers for specific format (serializer for JSONAPI missing in doc).

In most cases I use (de)normalizer just to change/add some data, but that is possible if you decorate the normalizer:

services:
    'App\Serializer\CustomItemNormalizer':
        decorates: 'api_platform.jsonld.normalizer.item'
        arguments: [ '@App\Serializer\CustomItemNormalizer.inner' ]

Link to decorating a serializer and adding extra data.

So at the end you need to inject the correct normalizer and decorate it.

like image 198
ilicmsreten Avatar answered Sep 20 '26 03:09

ilicmsreten