Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created October 30, 2014 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rican7/c6b1eb49265747bab1ab to your computer and use it in GitHub Desktop.
Save Rican7/c6b1eb49265747bab1ab to your computer and use it in GitHub Desktop.
AutomaticParamsParserRequest
<?php
use Klein\Request;
class AutomaticParamsParserRequest extends Request
{
/**
* Create a new request from the PHP request globals
*
* @see Klein\Request::createFromGlobals()
* @static
* @access public
* @return AutomaticParamsParserRequest
*/
public static function createFromGlobals()
{
// First, get our object from our parent handler
$request = parent::createFromGlobals();
// Should we even be handling params?
if ($request->method('POST')
|| $request->method('PUT')
|| $request->method('PATCH')
|| $request->method('DELETE')) {
// Parse Form URL Encoded attributes
if (strpos($request->headers()->get('content-type'), 'application/x-www-form-urlencoded') !== false
&& !$request->method('POST')) {
// Parse the body into a params array
parse_str($request->body(), $params);
// Replace the post params with the parse params
$request->paramsPost()->replace($params);
} elseif (strpos($request->headers()->get('content-type'), 'application/json') !== false
|| strpos($request->headers()->get('content-type'), 'application/x-json') !== false) {
// Decode the JSON body
$params = json_decode($request->body(), true);
// If there were no decoding errors
if (JSON_ERROR_NONE === json_last_error()) {
// Replace the post params with the parse params
$request->paramsPost()->replace((array) $params);
} else {
// Must have been a decoding error
throw new InvalidRequestSyntax();
}
}
}
return $request;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment