Skip to content

Instantly share code, notes, and snippets.

@VeryStrongFingers
Last active November 18, 2018 23:04
Show Gist options
  • Save VeryStrongFingers/6c1153f80eadd7b7051b to your computer and use it in GitHub Desktop.
Save VeryStrongFingers/6c1153f80eadd7b7051b to your computer and use it in GitHub Desktop.
Phalcon: Content-Type application/json support with Phalcon\Http\Request
<?php
namespace Pebkac\Phalcon\Http;
use Phalcon\Http\Request as HttpRequest;
/**
* Written to work with Phalcon 2.0.8
*/
class Request extends HttpRequest
{
protected $_postCache;
private $_isJson;
/**
* Determine (and store in memory) whether or not the current request content-type is application/json or not
* @return boolean
*/
private function isApplicationJson()
{
if(is_null($this->_isJson)){
$this->_isJson = (($contentType = $this->getDI()->getShared('request')->getHeader('CONTENT_TYPE')) && explode(';', $contentType)[0] === 'application/json');
}
return $this->_isJson;
}
public function getPut($name = NULL, $filters = NULL, $defaultValue = NULL, $notAllowEmpty = FALSE, $noRecursive = FALSE)
{
if(!is_array($this->_putCache)){
$this->_putCache = ($this->isApplicationJson()) ? (array)$this->getJsonRawBody() : $this->getRawBody();
}
return parent::getPut($name, $filters, $defaultValue, $notAllowEmpty, $noRecursive);
}
public function getPost($name = NULL, $filters = NULL, $defaultValue = NULL, $notAllowEmpty = FALSE, $noRecursive = FALSE)
{
if($this->isApplicationJson()){
if(is_null($this->_postCache)){
$this->_postCache = (array)$this->getJsonRawBody();
}
return $this->getHelper($this->_postCache, $name, $filters, $defaultValue, $notAllowEmpty, $notAllowEmpty);
} else {
return parent::getPost($name, $filters, $defaultValue, $notAllowEmpty, $noRecursive);
}
}
public function hasPost($name)
{
return array_key_exists($name, $this->getPost($name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment