Development

- Ensure that request-method is always lowercase.
- Fixed spaces instead of tabs to comply with PSR-2.
This commit is contained in:
Simon Sessingø
2016-11-25 12:51:45 +01:00
parent 2dd2d95af5
commit 1c515119b4
24 changed files with 3052 additions and 3066 deletions
+4 -4
View File
@@ -4,12 +4,12 @@ namespace Pecee\Http\Input;
interface IInputItem
{
public function getIndex();
public function getIndex();
public function getName();
public function getName();
public function getValue();
public function getValue();
public function __toString();
public function __toString();
}
+165 -192
View File
@@ -5,247 +5,220 @@ use Pecee\Http\Request;
class Input
{
/**
* @var array
*/
public $get = [];
/**
* @var array
*/
public $get = [];
/**
* @var array
*/
public $post = [];
/**
* @var array
*/
public $post = [];
/**
* @var array
*/
public $file = [];
/**
* @var array
*/
public $file = [];
/**
* @var Request
*/
protected $request;
/**
* @var Request
*/
protected $request;
protected $invalidContentType = false;
public function __construct(Request $request)
{
$this->request = $request;
protected $invalidContentTypes = [
'text/plain',
'application/x-www-form-urlencoded',
];
$this->parseInputs();
}
public function __construct(Request $request)
{
$this->request = $request;
protected function parseInputs()
{
/* Parse get requests */
if (count($_GET) > 0) {
$this->get = $this->handleGetPost($_GET);
}
if ($request->getMethod() !== 'get') {
/* Parse post requests */
$postVars = $_POST;
$requestContentType = $request->getHeader('http-content-type');
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete']) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
$max = count($this->invalidContentTypes) - 1;
if (count($postVars) > 0) {
$this->post = $this->handleGetPost($postVars);
}
for ($i = $max; $i >= 0; $i--) {
/* Parse get requests */
$contentType = $this->invalidContentType[$i];
if (count($_FILES) > 0) {
if (stripos($requestContentType, $contentType) === 0) {
$this->invalidContentType = true;
break;
}
}
}
$max = count($_FILES) - 1;
$keys = array_keys($_FILES);
if ($this->invalidContentType === false) {
$this->parseInputs();
}
for ($i = $max; $i >= 0; $i--) {
}
$key = $keys[$i];
$value = $_FILES[$key];
protected function parseInputs()
{
/* Parse get requests */
if (count($_GET) > 0) {
$this->get = $this->handleGetPost($_GET);
}
// Handle array input
if (is_array($value['name']) === false) {
$values['index'] = $key;
$this->file[$key] = InputFile::createFromArray(array_merge($value, $values));
continue;
}
/* Parse post requests */
$postVars = $_POST;
$subMax = count($value['name']) - 1;
$keys = array_keys($value['name']);
$output = [];
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete']) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
for ($i = $subMax; $i >= 0; $i--) {
if (count($postVars) > 0) {
$this->post = $this->handleGetPost($postVars);
}
$output[$keys[$i]] = InputFile::createFromArray([
'index' => $key,
'error' => $value['error'][$keys[$i]],
'tmp_name' => $value['tmp_name'][$keys[$i]],
'type' => $value['type'][$keys[$i]],
'size' => $value['size'][$keys[$i]],
'name' => $value['name'][$keys[$i]],
]);
/* Parse get requests */
}
if (count($_FILES) > 0) {
$this->file[$key] = $output;
}
}
}
$max = count($_FILES) - 1;
$keys = array_keys($_FILES);
protected function handleGetPost($array)
{
$tmp = [];
for ($i = $max; $i >= 0; $i--) {
$max = count($array) - 1;
$keys = array_keys($array);
$key = $keys[$i];
$value = $_FILES[$key];
for ($i = $max; $i >= 0; $i--) {
// Handle array input
if (is_array($value['name']) === false) {
$values['index'] = $key;
$this->file[$key] = InputFile::createFromArray(array_merge($value, $values));
continue;
}
$key = $keys[$i];
$value = $array[$key];
$subMax = count($value['name']) - 1;
$keys = array_keys($value['name']);
$output = [];
// Handle array input
if (is_array($value) === false) {
$tmp[$key] = new InputItem($key, $value);
continue;
}
for ($i = $subMax; $i >= 0; $i--) {
$subMax = count($value) - 1;
$keys = array_keys($value);
$output = [];
$output[$keys[$i]] = InputFile::createFromArray([
'index' => $key,
'error' => $value['error'][$keys[$i]],
'tmp_name' => $value['tmp_name'][$keys[$i]],
'type' => $value['type'][$keys[$i]],
'size' => $value['size'][$keys[$i]],
'name' => $value['name'][$keys[$i]],
]);
for ($i = $subMax; $i >= 0; $i--) {
$output[$keys[$i]] = new InputItem($key, $value[$keys[$i]]);
}
}
$tmp[$key] = $output;
}
$this->file[$key] = $output;
}
}
}
return $tmp;
}
protected function handleGetPost($array)
{
$tmp = [];
public function findPost($index, $default = null)
{
return isset($this->post[$index]) ? $this->post[$index] : $default;
}
$max = count($array) - 1;
$keys = array_keys($array);
public function findFile($index, $default = null)
{
return isset($this->file[$index]) ? $this->file[$index] : $default;
}
for ($i = $max; $i >= 0; $i--) {
public function findGet($index, $default = null)
{
return isset($this->get[$index]) ? $this->get[$index] : $default;
}
$key = $keys[$i];
$value = $array[$key];
public function getObject($index, $default = null, $method = null)
{
$element = null;
// Handle array input
if (is_array($value) === false) {
$tmp[$key] = new InputItem($key, $value);
continue;
}
if ($method === null || strtolower($method) === 'get') {
$element = $this->findGet($index);
}
$subMax = count($value) - 1;
$keys = array_keys($value);
$output = [];
if ($element === null && $method === null || strtolower($method) === 'post') {
$element = $this->findPost($index);
}
for ($i = $subMax; $i >= 0; $i--) {
$output[$keys[$i]] = new InputItem($key, $value[$keys[$i]]);
}
if ($element === null && $method === null || strtolower($method) === 'file') {
$element = $this->findFile($index);
}
$tmp[$key] = $output;
}
return ($element === null) ? $default : $element;
}
return $tmp;
}
/**
* Get input element value matching index
*
* @param string $index
* @param string|null $default
* @param string|null $method
* @return InputItem|string
*/
public function get($index, $default = null, $method = null)
{
$input = $this->getObject($index, $default, $method);
public function findPost($index, $default = null)
{
return isset($this->post[$index]) ? $this->post[$index] : $default;
}
if ($input instanceof InputItem) {
return (trim($input->getValue()) === '') ? $default : $input->getValue();
}
public function findFile($index, $default = null)
{
return isset($this->file[$index]) ? $this->file[$index] : $default;
}
return $input;
}
public function findGet($index, $default = null)
{
return isset($this->get[$index]) ? $this->get[$index] : $default;
}
public function exists($index)
{
return ($this->getObject($index) !== null);
}
public function getObject($index, $default = null, $method = null)
{
$element = null;
/**
* Get all get/post items
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null)
{
if ($this->invalidContentType === true) {
return [];
}
if ($method === null || strtolower($method) === 'get') {
$element = $this->findGet($index);
}
$output = $_POST;
if ($element === null && $method === null || strtolower($method) === 'post') {
$element = $this->findPost($index);
}
if ($this->request->getMethod() === 'post') {
if ($element === null && $method === null || strtolower($method) === 'file') {
$element = $this->findFile($index);
}
$contents = file_get_contents('php://input');
return ($element === null) ? $default : $element;
}
if (stripos(trim($contents), '{') === 0) {
$output = json_decode($contents, true);
if ($output === false) {
$output = [];
}
}
}
/**
* Get input element value matching index
*
* @param string $index
* @param string|null $default
* @param string|null $method
* @return InputItem|string
*/
public function get($index, $default = null, $method = null)
{
$input = $this->getObject($index, $default, $method);
$output = array_merge($_GET, $output);
if ($input instanceof InputItem) {
return (trim($input->getValue()) === '') ? $default : $input->getValue();
}
if ($filter !== null) {
$output = array_filter($output, function ($key) use ($filter) {
if (in_array($key, $filter)) {
return true;
}
return $input;
}
return false;
}, ARRAY_FILTER_USE_KEY);
}
public function exists($index)
{
return ($this->getObject($index) !== null);
}
/**
* Get all get/post items
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null)
{
if ($this->invalidContentType === true) {
return [];
}
$output = $_POST;
if ($this->request->getMethod() === 'post') {
$contents = file_get_contents('php://input');
if (stripos(trim($contents), '{') === 0) {
$output = json_decode($contents, true);
if ($output === false) {
$output = [];
}
}
}
$output = array_merge($_GET, $output);
if ($filter !== null) {
$output = array_filter($output, function ($key) use ($filter) {
if (in_array($key, $filter)) {
return true;
}
return false;
}, ARRAY_FILTER_USE_KEY);
}
return $output;
}
return $output;
}
}
+155 -155
View File
@@ -3,188 +3,188 @@ namespace Pecee\Http\Input;
class InputFile implements IInputItem
{
public $index;
public $name;
public $size;
public $type;
public $error;
public $tmpName;
public $index;
public $name;
public $size;
public $type;
public $error;
public $tmpName;
public function __construct($index)
{
$this->index = $index;
public function __construct($index)
{
$this->index = $index;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getSize()
{
return $this->size;
}
/**
* @return string
*/
public function getSize()
{
return $this->size;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @return string
*/
public function getError()
{
return $this->error;
}
public function getMime()
{
return $this->getType();
}
public function getMime()
{
return $this->getType();
}
/**
* @return string
*/
public function getTmpName()
{
return $this->tmpName;
}
/**
* @return string
*/
public function getTmpName()
{
return $this->tmpName;
}
public function getExtension()
{
return pathinfo($this->getName(), PATHINFO_EXTENSION);
}
public function getExtension()
{
return pathinfo($this->getName(), PATHINFO_EXTENSION);
}
public function move($destination)
{
return move_uploaded_file($this->tmpName, $destination);
}
public function move($destination)
{
return move_uploaded_file($this->tmpName, $destination);
}
public function getContents()
{
return file_get_contents($this->tmpName);
}
public function getContents()
{
return file_get_contents($this->tmpName);
}
public function setName($name)
{
$this->name = $name;
public function setName($name)
{
$this->name = $name;
return $this;
}
return $this;
}
/**
* Set file temp. name
* @param string $name
* @return static $this
*/
public function setTmpName($name)
{
$this->tmpName = $name;
/**
* Set file temp. name
* @param string $name
* @return static $this
*/
public function setTmpName($name)
{
$this->tmpName = $name;
return $this;
}
return $this;
}
/**
* Set file size
* @param int $size
* @return static $this
*/
public function setSize($size)
{
$this->size = $size;
/**
* Set file size
* @param int $size
* @return static $this
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
return $this;
}
/**
* Set type
* @param string $type
* @return static $this
*/
public function setType($type)
{
$this->type = $type;
/**
* Set type
* @param string $type
* @return static $this
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
return $this;
}
/**
* Set error
* @param int $error
* @return static $this
*/
public function setError($error)
{
$this->error = (int)$error;
/**
* Set error
* @param int $error
* @return static $this
*/
public function setError($error)
{
$this->error = (int)$error;
return $this;
}
return $this;
}
public function getValue()
{
return $this->getTmpName();
}
public function getValue()
{
return $this->getTmpName();
}
public function hasError()
{
return ($this->getError() !== 0);
}
public function hasError()
{
return ($this->getError() !== 0);
}
/**
* Create from array
* @param array $values
* @return static
*/
public static function createFromArray(array $values)
{
if (!isset($values['index'])) {
throw new \InvalidArgumentException('Index key is required');
}
/**
* Create from array
* @param array $values
* @return static
*/
public static function createFromArray(array $values)
{
if (!isset($values['index'])) {
throw new \InvalidArgumentException('Index key is required');
}
$input = new static($values['index']);
$input->setError(isset($values['error']) ? $values['error'] : null);
$input->setName(isset($values['name']) ? $values['name'] : null);
$input->setSize(isset($values['size']) ? $values['size'] : null);
$input->setType(isset($values['type']) ? $values['type'] : null);
$input->setTmpName(isset($values['tmp_name']) ? $values['tmp_name'] : null);
$input = new static($values['index']);
$input->setError(isset($values['error']) ? $values['error'] : null);
$input->setName(isset($values['name']) ? $values['name'] : null);
$input->setSize(isset($values['size']) ? $values['size'] : null);
$input->setType(isset($values['type']) ? $values['type'] : null);
$input->setTmpName(isset($values['tmp_name']) ? $values['tmp_name'] : null);
return $input;
}
return $input;
}
public function toArray()
{
return [
'tmp_name' => $this->tmpName,
'type' => $this->type,
'size' => $this->size,
'name' => $this->name,
'error' => $this->error,
];
}
public function toArray()
{
return [
'tmp_name' => $this->tmpName,
'type' => $this->type,
'size' => $this->size,
'name' => $this->name,
'error' => $this->error,
];
}
public function __toString()
{
return $this->getValue();
}
public function __toString()
{
return $this->getValue();
}
}
+57 -55
View File
@@ -3,68 +3,70 @@ namespace Pecee\Http\Input;
class InputItem implements IInputItem
{
public $index;
public $name;
public $value;
public $index;
public $name;
public $value;
public function __construct($index, $value = null)
{
$this->index = $index;
$this->value = $value;
public function __construct($index, $value = null)
{
$this->index = $index;
$this->value = $value;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set input name
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Set input name
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
/**
* Set input value
* @param string $value
* @return static $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
return $this;
}
public function __toString()
{
return (string)$this->value;
}
/**
* Set input value
* @param string $value
* @return static $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
public function __toString()
{
return (string)$this->value;
}
}
+68 -67
View File
@@ -8,92 +8,93 @@ use Pecee\SimpleRouter\Route\ILoadableRoute;
class BaseCsrfVerifier implements IMiddleware
{
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $csrfToken;
protected $token;
protected $except;
protected $csrfToken;
protected $token;
public function __construct()
{
$this->csrfToken = new CsrfToken();
public function __construct()
{
$this->csrfToken = new CsrfToken();
// Generate or get the CSRF-Token from Cookie.
$this->token = ($this->hasToken() === false) ? $this->generateToken() : $this->csrfToken->getToken();
}
// Generate or get the CSRF-Token from Cookie.
$this->token = ($this->hasToken() === false) ? $this->generateToken() : $this->csrfToken->getToken();
}
/**
* Check if the url matches the urls in the except property
* @param Request $request
* @return bool
*/
protected function skip(Request $request)
{
if ($this->except === null || is_array($this->except) === false) {
return false;
}
/**
* Check if the url matches the urls in the except property
* @param Request $request
* @return bool
*/
protected function skip(Request $request)
{
if ($this->except === null || is_array($this->except) === false) {
return false;
}
$max = count($this->except) - 1;
$max = count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
$url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUri(), $url) === 0);
} else {
$skip = ($url === rtrim($request->getUri(), '/'));
}
$url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUri(), $url) === 0);
} else {
$skip = ($url === rtrim($request->getUri(), '/'));
}
if ($skip === true) {
return true;
}
}
if ($skip === true) {
return true;
}
}
return false;
}
return false;
}
public function handle(Request $request, ILoadableRoute &$route = null)
{
public function handle(Request $request, ILoadableRoute &$route = null)
{
if (in_array($request->getMethod(), ['post', 'put', 'delete']) === true && $this->skip($request) === false) {
if (in_array($request->getMethod(), ['post', 'put', 'delete']) === true && $this->skip($request) === false) {
$token = $request->getInput()->get(static::POST_KEY, null, 'post');
$token = $request->getInput()->get(static::POST_KEY, null, 'post');
// If the token is not posted, check headers for valid x-csrf-token
if ($token === null) {
$token = $request->getHeader(static::HEADER_KEY);
}
// If the token is not posted, check headers for valid x-csrf-token
if ($token === null) {
$token = $request->getHeader(static::HEADER_KEY);
}
if ($this->csrfToken->validate($token) === false) {
throw new TokenMismatchException('Invalid csrf-token.');
}
if ($this->csrfToken->validate($token) === false) {
throw new TokenMismatchException('Invalid csrf-token.');
}
}
}
}
}
public function generateToken()
{
$token = $this->csrfToken->generateToken();
$this->csrfToken->setToken($token);
return $token;
}
public function generateToken()
{
$token = $this->csrfToken->generateToken();
$this->csrfToken->setToken($token);
public function hasToken()
{
if ($this->token != null) {
return true;
}
return $token;
}
return $this->csrfToken->hasToken();
}
public function hasToken()
{
if ($this->token != null) {
return true;
}
public function getToken()
{
return $this->token;
}
return $this->csrfToken->hasToken();
}
public function getToken()
{
return $this->token;
}
}
+6 -6
View File
@@ -6,11 +6,11 @@ use Pecee\SimpleRouter\Route\ILoadableRoute;
interface IMiddleware
{
/**
* @param Request $request
* @param ILoadableRoute $route
* @return Request|null
*/
public function handle(Request $request, ILoadableRoute &$route);
/**
* @param Request $request
* @param ILoadableRoute $route
* @return Request|null
*/
public function handle(Request $request, ILoadableRoute &$route);
}
+188 -188
View File
@@ -5,226 +5,226 @@ use Pecee\Http\Input\Input;
class Request
{
protected $data = [];
protected $headers;
protected $host;
protected $uri;
protected $method;
protected $input;
protected $data = [];
protected $headers;
protected $host;
protected $uri;
protected $method;
protected $input;
public function __construct()
{
$this->parseHeaders();
$this->host = $this->getHeader('http-host');;
$this->uri = $this->getHeader('request-uri');
$this->input = new Input($this);
$this->method = $this->input->get('_method', strtolower($this->getHeader('request-method')));
}
public function __construct()
{
$this->parseHeaders();
$this->host = $this->getHeader('http-host');;
$this->uri = $this->getHeader('request-uri');
$this->input = new Input($this);
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method')));
}
protected function parseHeaders()
{
$this->headers = [];
protected function parseHeaders()
{
$this->headers = [];
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
for($i = $max; $i >= 0; $i--) {
$key = $keys[$i];
$value = $_SERVER[$key];
for ($i = $max; $i >= 0; $i--) {
$key = $keys[$i];
$value = $_SERVER[$key];
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
}
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
}
}
}
public function isSecure()
{
if ($this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443) {
return true;
}
public function isSecure()
{
if ($this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443) {
return true;
}
return false;
}
return false;
}
/**
* @return string
*/
public function getUri()
{
return $this->uri;
}
/**
* @return string
*/
public function getUri()
{
return $this->uri;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Get http basic auth user
* @return string|null
*/
public function getUser()
{
return $this->getHeader('php-auth-user');
}
/**
* Get http basic auth user
* @return string|null
*/
public function getUser()
{
return $this->getHeader('php-auth-user');
}
/**
* Get http basic auth password
* @return string|null
*/
public function getPassword()
{
return $this->getHeader('php-auth-pw');
}
/**
* Get http basic auth password
* @return string|null
*/
public function getPassword()
{
return $this->getHeader('php-auth-pw');
}
/**
* Get all headers
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get all headers
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get id address
* @return string
*/
public function getIp()
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
}
/**
* Get id address
* @return string
*/
public function getIp()
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
}
if ($this->getHeader('http-x-forwarded-for') !== null && strlen($this->getHeader('http-x-forwarded-for'))) {
return $this->getHeader('http-x-forwarded_for');
}
if ($this->getHeader('http-x-forwarded-for') !== null && strlen($this->getHeader('http-x-forwarded-for'))) {
return $this->getHeader('http-x-forwarded_for');
}
return $this->getHeader('remote-addr');
}
return $this->getHeader('remote-addr');
}
/**
* Get referer
* @return string
*/
public function getReferer()
{
return $this->getHeader('http-referer');
}
/**
* Get referer
* @return string
*/
public function getReferer()
{
return $this->getHeader('http-referer');
}
/**
* Get user agent
* @return string
*/
public function getUserAgent()
{
return $this->getHeader('http-user-agent');
}
/**
* Get user agent
* @return string
*/
public function getUserAgent()
{
return $this->getHeader('http-user-agent');
}
/**
* Get header value by name
*
* @param string $name
* @param object|null $defaultValue
*
* @return string|null
*/
public function getHeader($name, $defaultValue = null)
{
if (isset($this->headers[strtolower($name)])) {
return $this->headers[strtolower($name)];
}
/**
* Get header value by name
*
* @param string $name
* @param object|null $defaultValue
*
* @return string|null
*/
public function getHeader($name, $defaultValue = null)
{
if (isset($this->headers[strtolower($name)])) {
return $this->headers[strtolower($name)];
}
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
for ($i = $max; $i >= 0; $i--) {
for ($i = $max; $i >= 0; $i--) {
$key = $keys[$i];
$name = $_SERVER[$key];
$key = $keys[$i];
$name = $_SERVER[$key];
if ($key === $name) {
return $name;
}
}
if ($key === $name) {
return $name;
}
}
return $defaultValue;
}
return $defaultValue;
}
/**
* Get input class
* @return Input
*/
public function getInput()
{
return $this->input;
}
/**
* Get input class
* @return Input
*/
public function getInput()
{
return $this->input;
}
/**
* Is format accepted
*
* @param string $format
*
* @return bool
*/
public function isFormatAccepted($format)
{
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
}
/**
* Is format accepted
*
* @param string $format
*
* @return bool
*/
public function isFormatAccepted($format)
{
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
}
/**
* Get accept formats
* @return array
*/
public function getAcceptFormats()
{
return explode(',', $this->getHeader('http-accept'));
}
/**
* Get accept formats
* @return array
*/
public function getAcceptFormats()
{
return explode(',', $this->getHeader('http-accept'));
}
/**
* @param string $uri
*/
public function setUri($uri)
{
$this->uri = $uri;
}
/**
* @param string $uri
*/
public function setUri($uri)
{
$this->uri = $uri;
}
/**
* @param string $host
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* @param string $host
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* @param string $method
*/
public function setMethod($method)
{
$this->method = $method;
}
/**
* @param string $method
*/
public function setMethod($method)
{
$this->method = $method;
}
public function __set($name, $value = null)
{
$this->data[$name] = $value;
}
public function __set($name, $value = null)
{
$this->data[$name] = $value;
}
public function __get($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
public function __get($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
}
+99 -95
View File
@@ -3,116 +3,120 @@ namespace Pecee\Http;
class Response
{
protected $request;
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Set the http status code
*
* @param int $code
* @return static
*/
public function httpCode($code)
{
http_response_code($code);
return $this;
}
/**
* Set the http status code
*
* @param int $code
* @return static
*/
public function httpCode($code)
{
http_response_code($code);
/**
* Redirect the response
*
* @param string $url
* @param int $httpCode
*/
public function redirect($url, $httpCode = null)
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
}
return $this;
}
$this->header('location: ' . $url);
die();
}
/**
* Redirect the response
*
* @param string $url
* @param int $httpCode
*/
public function redirect($url, $httpCode = null)
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
}
public function refresh()
{
$this->redirect($this->request->getUri());
}
$this->header('location: ' . $url);
die();
}
/**
* Add http authorisation
* @param string $name
* @return static
*/
public function auth($name = '')
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
'HTTP/1.0 401 Unauthorized'
]);
return $this;
}
public function refresh()
{
$this->redirect($this->request->getUri());
}
public function cache($eTag, $lastModified = 2592000)
{
/**
* Add http authorisation
* @param string $name
* @return static
*/
public function auth($name = '')
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
'HTTP/1.0 401 Unauthorized',
]);
$this->headers([
'Cache-Control: public',
'Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT',
'Etag: ' . $eTag
]);
return $this;
}
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
public function cache($eTag, $lastModified = 2592000)
{
if ($httpModified !== null && strtotime($httpModified) == $lastModified || $httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) {
$this->headers([
'Cache-Control: public',
'Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT',
'Etag: ' . $eTag,
]);
$this->header('HTTP/1.1 304 Not Modified');
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
exit();
}
if ($httpModified !== null && strtotime($httpModified) == $lastModified || $httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) {
return $this;
}
$this->header('HTTP/1.1 304 Not Modified');
/**
* Json encode array
* @param array $value
*/
public function json(array $value)
{
$this->header('Content-Type: application/json');
echo json_encode($value);
die();
}
exit();
}
/**
* Add header to response
* @param string $value
* @return static
*/
public function header($value)
{
header($value);
return $this;
}
return $this;
}
/**
* Add multiple headers to response
* @param array $headers
* @return static
*/
public function headers(array $headers)
{
$max = count($headers);
for($i = 0; $i < $max; $i++) {
$this->header($headers[$i]);
}
return $this;
}
/**
* Json encode array
* @param array $value
*/
public function json(array $value)
{
$this->header('Content-Type: application/json');
echo json_encode($value);
die();
}
/**
* Add header to response
* @param string $value
* @return static
*/
public function header($value)
{
header($value);
return $this;
}
/**
* Add multiple headers to response
* @param array $headers
* @return static
*/
public function headers(array $headers)
{
$max = count($headers);
for ($i = 0; $i < $max; $i++) {
$this->header($headers[$i]);
}
return $this;
}
}