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

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

Open
wants to merge 1 commit into
base: 3.x
Choose a base branch
from

Conversation

damienfa
Copy link

@damienfa damienfa commented Oct 9, 2020

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. 😉

A Decoder may be applied to the Request content but the application (or a third bundle used by the application), this way we're able to know if a decoder has been applied (and which).
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

Successfully merging this pull request may close these issues.

1 participant