Reputation: 145
I am looking for a way to use a custom normalizer based on some conditions. Conditions being dependent on some parameter in the URL.
The normalizer I created gets autowired automatically, but I want to use it ONLY if a parameter is passed in the URL.
Is there a way to do this? Dynamically add the normalizer to the container in a request listener?
Currently if I set autoconfigure to true
, it uses my normalizer, and set to false
, it does not get used. But I need to make this configuration outside of the services.yml
file.
#services.yaml
App\Framework\Serializer\CustomNormalizer:
autoconfigure: false
Upvotes: 1
Views: 862
Reputation: 47613
That's not how autowiring works. You'll need to put your logic somewhere else. Container compilation happens before any request is made, so it cannot be made dependant on parameters values.
But you can use the supportsNomralization()
method and the $context
to decide to use your normalizer or not.
public function supportsNormalization($data, string $format = null, array $context = [])
{
if (!$data instanceof Foo) {
return false;
}
if (!\array_key_exists('foo_bar', $context) || $context['foo_bar'] !== '1') {
return false;
}
return true;
}
And then when serializing your Foo
, pass the appropriate parameter in the context if the parameter comes in the request:
$fooBar = $request->query->get('foo_bar');
$normalized = $this->serializer->normalize($someFoo, ['foo_bar' => $fooBar]);
This is a simple, untested example, but you should get the general idea to implement your own.
Again, implementing this on the DI layer is a no-go. The DI container is compiled ahead of time, so there is no information about the request there (nor should be).
Upvotes: 1