1

I'm trying to migrate an existing web app to the Lithium framework.

If I POST JSON-encoded data to an URL and set the Content-Type header to application/json on the request, the POST'd data is automatically parsed and available in the controller (as $this->request->data). Hooray.

However, I need to support a client app which does not set the Content-Type header properly. In this case, the framework assumes it is URL-encoded form data and attempts to parse it as such.

Is there any way to override the request's Content-Type for a particular URL, in time for it to be parsed correctly?

benzado
  • 82,288
  • 22
  • 110
  • 138
  • In your controller, couldn't you detect the url and/or check if data appears unsubmitted, and perform the data decoding for the `Request` object? – Jared Farrish Dec 21 '11 at 06:18
  • @JaredFarrish If all else fails I could probably do something like that, but I'd like to keep the parsing out of the controller if I can. – benzado Dec 22 '11 at 06:06

1 Answers1

1

Try the following in your bootstrap.php script. If the request data array only has one item in it, and that item can be decoded, the request data is replaced with the decoded json data.

use \lithium\action\Dispatcher;

Dispatcher::applyFilter('run', function($self, $params, $chain) {

    // Only check for JSON data for a certain URL
    if($params['request']->url == 'your/url/here') {

        // If the data array only has one element and the key can be decoded as
        // JSON data, replace the request data with the decoded JSON array
        if(count($params['request']->data) == 1) {
            $keys = array_keys($params['request']->data);
            $data = $keys[0];
            if(($data = json_decode($data, true)) != null) {
                $params['request']->data = $data;
            }
        }
    }

    return $chain->next($self, $params, $chain);

});
psparrow
  • 9,808
  • 1
  • 17
  • 11
  • Thanks! This did the trick, though I read from 'php://input' instead of using the data array (since a stray '&' would have it parse as multiple keys and values). – benzado Dec 30 '11 at 05:30