FriendsOfSymfony / FOSRestBundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony
http://symfony.com/doc/master/bundles/FOSRestBundle/index.html
MIT License
2.79k stars 704 forks source link

Indicate to the Symfony Request attributes which Decoder has been used #2272

Open damienfa opened 3 years ago

damienfa commented 3 years ago

Context :

I'm working on a Symfony bundle. From a view, an Ajax request (application/json) is sent to a Controller managed by my bundle. The bundle have not FOSRestBundle because we don't really want to add a new dependency in our code base (and only one Rest request). BUT, the main Symfony application (which use our custom bundle) may be using the FOSRestBundle (and it often does).

For example, the main application could declare a Json Decoder :

fos_rest: 
    body_listener:
        decoders:
            json: fos_rest.decoder.json

My issue / question 🤔 :

The Controller, inside the bundle, doesn't really know if the Json Request received has already been "decoded" by a FOSRestBundle Json Decoder. Where can we find this information inside the Request ? (checking the app configuration is overkill I guess !). Therefore, we manually decode the request without the help of FOSRestBundle (which is a pity because the FOSRestBundle is often present in the applications which use our custom bundle).

Exemple of code at the beggining of my Controller action :

if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
     $jsonData = @json_decode($request->getContent(), true); // Convert raw request content
     $request->request->replace(is_array($jsonData) ? $jsonData : []); // replace request array
}

Proposition 😃 :

The Request object have some "attributes", FOSRestBundle could add some custom metadata to tell the Request which Decoder as been used. I propose to set the Decoder class name inside an "_fosrestbundle_decoder" Request attribute. So, in my bundle, I will be able to easily check if FOSRestBundle has already done the job or if I have to do it by myself. 😉