-
-
Save Rican7/c6b1eb49265747bab1ab to your computer and use it in GitHub Desktop.
AutomaticParamsParserRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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