v4-development sync & getIp() update to new header method

This commit is contained in:
DeveloperMarius
2021-03-22 22:25:37 +01:00
34 changed files with 472 additions and 1288 deletions
+99 -26
View File
@@ -27,6 +27,24 @@ class InputHandler
*/
protected $request;
/**
* Original post variables
* @var array
*/
protected $originalPost = [];
/**
* Original get/params variables
* @var array
*/
protected $originalParams = [];
/**
* Get original file variables
* @var array
*/
protected $originalFile = [];
/**
* Input constructor.
* @param Request $request
@@ -46,22 +64,34 @@ class InputHandler
{
/* Parse get requests */
if (\count($_GET) !== 0) {
$this->get = $this->parseInputItem($_GET);
$this->originalParams = $_GET;
$this->get = $this->parseInputItem($this->originalParams);
}
/* Parse post requests */
$postVars = $_POST;
$this->originalPost = $_POST;
if (\in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
parse_str(file_get_contents('php://input'), $postVars);
if (\in_array($this->request->getMethod(), Request::$requestTypesPost, false) === true) {
$contents = file_get_contents('php://input');
// Append any PHP-input json
if (strpos(trim($contents), '{') === 0) {
$post = json_decode($contents, true);
if ($post !== false) {
$this->originalPost += $post;
}
}
}
if (\count($postVars) !== 0) {
$this->post = $this->parseInputItem($postVars);
if (\count($this->originalPost) !== 0) {
$this->post = $this->parseInputItem($this->originalPost);
}
/* Parse get requests */
if (\count($_FILES) !== 0) {
$this->originalFile = $_FILES;
$this->file = $this->parseFiles();
}
}
@@ -192,11 +222,11 @@ class InputHandler
{
$element = null;
if (\count($methods) === 0 || \in_array('get', $methods, true) === true) {
if (\count($methods) === 0 || \in_array(Request::REQUEST_TYPE_GET, $methods, true) === true) {
$element = $this->get($index);
}
if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array('post', $methods, true) === true)) {
if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array(Request::REQUEST_TYPE_POST, $methods, true) === true)) {
$element = $this->post($index);
}
@@ -288,24 +318,7 @@ class InputHandler
*/
public function all(array $filter = []): array
{
$output = $_GET;
if ($this->request->getMethod() === 'post') {
// Append POST data
$output += $_POST;
$contents = file_get_contents('php://input');
// Append any PHP-input json
if (strpos(trim($contents), '{') === 0) {
$post = json_decode($contents, true);
if ($post !== false) {
$output += $post;
}
}
}
$output = $this->originalParams + $this->originalPost + $this->originalFile;
$output = (\count($filter) > 0) ? array_intersect_key($output, array_flip($filter)) : $output;
foreach ($filter as $filterKey) {
@@ -350,4 +363,64 @@ class InputHandler
$this->file[$key] = $item;
}
/**
* Get original post variables
* @return array
*/
public function getOriginalPost(): array
{
return $this->originalPost;
}
/**
* Set original post variables
* @param array $post
* @return static $this
*/
public function setOriginalPost(array $post): self
{
$this->originalPost = $post;
return $this;
}
/**
* Get original get variables
* @return array
*/
public function getOriginalParams(): array
{
return $this->originalParams;
}
/**
* Set original get-variables
* @param array $params
* @return static $this
*/
public function setOriginalParams(array $params): self
{
$this->originalParams = $params;
return $this;
}
/**
* Get original file variables
* @return array
*/
public function getOriginalFile(): array
{
return $this->originalFile;
}
/**
* Set original file posts variables
* @param array $file
* @return static $this
*/
public function setOriginalFile(array $file): self
{
$this->originalFile = $file;
return $this;
}
}
+1 -4
View File
@@ -2,9 +2,6 @@
namespace Pecee\Http\Input;
use Exception;
use Traversable;
class InputItem implements IInputItem, \IteratorAggregate
{
public $index;
@@ -81,7 +78,7 @@ class InputItem implements IInputItem, \IteratorAggregate
return (\is_array($value) === true) ? json_encode($value) : $value;
}
public function getIterator()
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->getValue());
}
@@ -63,13 +63,12 @@ class BaseCsrfVerifier implements IMiddleware
*/
public function handle(Request $request): void
{
if ($this->skip($request) === false && \in_array($request->getMethod(), ['post', 'put', 'delete'], true) === true) {
if ($this->skip($request) === false && \in_array($request->getMethod(), Request::$requestTypesPost, true) === true) {
$token = $request->getInputHandler()->value(
static::POST_KEY,
$request->getHeader(static::HEADER_KEY),
'post'
Request::$requestTypesPost
);
if ($this->tokenProvider->validate((string)$token) === false) {
@@ -80,7 +79,6 @@ class BaseCsrfVerifier implements IMiddleware
// Refresh existing token
$this->tokenProvider->refresh();
}
public function getTokenProvider(): ITokenProvider
+70 -6
View File
@@ -4,12 +4,46 @@ namespace Pecee\Http;
use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Input\InputHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter;
class Request
{
public const REQUEST_TYPE_GET = 'get';
public const REQUEST_TYPE_POST = 'post';
public const REQUEST_TYPE_PUT = 'put';
public const REQUEST_TYPE_PATCH = 'patch';
public const REQUEST_TYPE_OPTIONS = 'options';
public const REQUEST_TYPE_DELETE = 'delete';
public const REQUEST_TYPE_HEAD = 'head';
/**
* All request-types
* @var string[]
*/
public static $requestTypes = [
self::REQUEST_TYPE_GET,
self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT,
self::REQUEST_TYPE_PATCH,
self::REQUEST_TYPE_OPTIONS,
self::REQUEST_TYPE_DELETE,
self::REQUEST_TYPE_HEAD,
];
/**
* Post request-types.
* @var string[]
*/
public static $requestTypesPost = [
self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT,
self::REQUEST_TYPE_PATCH,
self::REQUEST_TYPE_DELETE,
];
/**
* Additional data
*
@@ -77,14 +111,14 @@ class Request
{
foreach ($_SERVER as $key => $value) {
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
$this->headers[str_replace('_', '-', strtolower($key))] = $value;
}
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
$this->setUrl(new Url($this->getHeader('unencoded-url', $this->getHeader('request-uri'))));
$this->method = strtolower($this->getHeader('request-method'));
$this->inputHandler = new InputHandler($this);
$this->method = strtolower($this->inputHandler->value('_method', $this->getHeader('request-method')));
@@ -147,6 +181,15 @@ class Request
return $this->getHeader('php-auth-pw');
}
/**
* Get the csrf token
* @return string|null
*/
public function getCsrfToken(): ?string
{
return $this->getHeader(BaseCsrfVerifier::HEADER_KEY);
}
/**
* Get all headers
* @return array
@@ -165,6 +208,13 @@ class Request
*/
public function getIp(bool $safe = false): ?string
{
return $this->getHeader(
'http-cf-connecting-ip',
$this->getHeader(
'http-x-forwarded-for',
$this->getHeader('remote-addr')
)
);
$client_header = null;
if(!$safe){
if ($this->getHeader('http-cf-connecting-ip') !== null) {
@@ -212,14 +262,28 @@ class Request
/**
* Get header value by name
*
* @param string $name
* @param string|null $defaultValue
* @param string $name Name of the header.
* @param string|null $defaultValue Value to be returned if header is not found.
* @param bool $tryParse When enabled the method will try to find the header from both from client (http) and server-side variants, if the header is not found.
*
* @return string|null
*/
public function getHeader($name, $defaultValue = null): ?string
public function getHeader(string $name, $defaultValue = null, $tryParse = true): ?string
{
return $this->headers[strtolower($name)] ?? $defaultValue;
$name = strtolower($name);
$header = $this->headers[$name] ?? null;
if ($tryParse === true && $header === null) {
if (strpos($name, 'http-') === 0) {
// Trying to find client header variant which was not found, searching for header variant without http- prefix.
$header = $this->headers[str_replace('http-', '', $name)] ?? null;
} else {
// Trying to find server variant which was not found, searching for client variant with http- prefix.
$header = $this->headers['http-' . $name] ?? null;
}
}
return $header ?? $defaultValue;
}
/**
@@ -48,7 +48,7 @@ class ClassLoader implements IClassLoader
/**
* Load closure
*
* @param \Closure $closure
* @param Callable $closure
* @param array $parameters
* @return mixed
* @throws NotFoundHttpException
+16 -2
View File
@@ -22,8 +22,8 @@ interface IRoute
*
* @param Request $request
* @param Router $router
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return string
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
*/
public function renderRoute(Request $request, Router $router): ?string;
@@ -82,7 +82,7 @@ interface IRoute
/**
* Set callback
*
* @param string $callback
* @param string|array|\Closure $callback
* @return static
*/
public function setCallback($callback): self;
@@ -206,4 +206,18 @@ interface IRoute
*/
public function setMiddlewares(array $middlewares): self;
/**
* If enabled parameters containing null-value will not be passed along to the callback.
*
* @param bool $enabled
* @return static $this
*/
public function setFilterEmptyParams(bool $enabled): self;
/**
* Status if filtering of empty params is enabled or disabled
* @return bool
*/
public function getFilterEmptyParams(): bool;
}
@@ -60,7 +60,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return null;
}
return ((bool)preg_match($this->regex, $request->getHost() . $url) !== false);
return ((bool)preg_match($this->regex, $url) !== false);
}
/**
+41 -33
View File
@@ -10,25 +10,7 @@ use Pecee\SimpleRouter\Router;
abstract class Route implements IRoute
{
protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
protected const PARAMETERS_DEFAULT_REGEX = '[\w\-]+';
public const REQUEST_TYPE_GET = 'get';
public const REQUEST_TYPE_POST = 'post';
public const REQUEST_TYPE_PUT = 'put';
public const REQUEST_TYPE_PATCH = 'patch';
public const REQUEST_TYPE_OPTIONS = 'options';
public const REQUEST_TYPE_DELETE = 'delete';
public const REQUEST_TYPE_HEAD = 'head';
public static $requestTypes = [
self::REQUEST_TYPE_GET,
self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT,
self::REQUEST_TYPE_PATCH,
self::REQUEST_TYPE_OPTIONS,
self::REQUEST_TYPE_DELETE,
self::REQUEST_TYPE_HEAD,
];
protected const PARAMETERS_DEFAULT_REGEX = '[\w-]+';
/**
* If enabled parameters containing null-value
@@ -99,22 +81,19 @@ abstract class Route implements IRoute
return $router->getClassLoader()->loadClosure($callback, $parameters);
}
/* When the callback is a class + method */
$controller = explode('@', $callback);
$controller = $this->getClass();
$method = $this->getMethod();
$namespace = $this->getNamespace();
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
$className = ($namespace !== null && $controller[0] !== '\\') ? $namespace . '\\' . $controller : $controller;
$router->debug('Loading class %s', $className);
$class = $router->getClassLoader()->loadClass($className);
if (\count($controller) === 1) {
if ($method === null) {
$controller[1] = '__invoke';
}
$method = $controller[1];
if (method_exists($class, $method) === false) {
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
}
@@ -144,7 +123,7 @@ abstract class Route implements IRoute
$urlRegex = preg_quote($route, '/');
} else {
foreach (preg_split('/((\-?\/?)\{[^}]+\})/', $route) as $key => $t) {
foreach (preg_split('/((-?\/?){[^}]+})/', $route) as $key => $t) {
$regex = '';
@@ -159,7 +138,7 @@ abstract class Route implements IRoute
$regex = $parameterRegex ?? $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
}
$regex = sprintf('((\/|\-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
$regex = sprintf('((\/|-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
}
$urlRegex .= preg_quote($t, '/') . $regex;
@@ -271,7 +250,7 @@ abstract class Route implements IRoute
/**
* Set callback
*
* @param string $callback
* @param string|array\Closure $callback
* @return static
*/
public function setCallback($callback): IRoute
@@ -291,6 +270,10 @@ abstract class Route implements IRoute
public function getMethod(): ?string
{
if (\is_array($this->callback) === true && \count($this->callback) > 1) {
return $this->callback[1];
}
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
@@ -302,6 +285,10 @@ abstract class Route implements IRoute
public function getClass(): ?string
{
if (\is_array($this->callback) === true && \count($this->callback) > 0) {
return $this->callback[0];
}
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
@@ -313,14 +300,14 @@ abstract class Route implements IRoute
public function setMethod(string $method): IRoute
{
$this->callback = sprintf('%s@%s', $this->getClass(), $method);
$this->callback = [$this->getClass(), $method];
return $this;
}
public function setClass(string $class): IRoute
{
$this->callback = sprintf('%s@%s', $class, $this->getMethod());
$this->callback = [$class, $this->getMethod()];
return $this;
}
@@ -456,9 +443,9 @@ abstract class Route implements IRoute
* Add regular expression parameter match.
* Alias for LoadableRoute::where()
*
* @see LoadableRoute::where()
* @param array $options
* @return static
* @see LoadableRoute::where()
*/
public function where(array $options)
{
@@ -506,9 +493,9 @@ abstract class Route implements IRoute
/**
* Add middleware class-name
*
* @deprecated This method is deprecated and will be removed in the near future.
* @param IMiddleware|string $middleware
* @return static
* @deprecated This method is deprecated and will be removed in the near future.
*/
public function setMiddleware($middleware)
{
@@ -575,4 +562,25 @@ abstract class Route implements IRoute
return $this->defaultParameterRegex;
}
/**
* If enabled parameters containing null-value will not be passed along to the callback.
*
* @param bool $enabled
* @return static $this
*/
public function setFilterEmptyParams(bool $enabled): IRoute
{
$this->filterEmptyParams = $enabled;
return $this;
}
/**
* Status if filtering of empty params is enabled or disabled
* @return bool
*/
public function getFilterEmptyParams(): bool
{
return $this->filterEmptyParams;
}
}
@@ -64,7 +64,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
if ($method !== null) {
/* Remove requestType from method-name, if it exists */
foreach (static::$requestTypes as $requestType) {
foreach (Request::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, \strlen($requestType));
@@ -110,7 +110,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$this->parameters = \array_slice($path, 1);
// Set callback
$this->setCallback($this->controller . '@' . $this->method);
$this->setCallback([$this->controller, $this->method]);
return true;
}
+9 -1
View File
@@ -52,8 +52,16 @@ class RouteGroup extends Route implements IGroupRoute
return false;
}
// Parse parameter
$prefix = $this->prefix;
foreach($this->getParameters() as $parameter => $value) {
$prefix = str_ireplace('{' . $parameter . '}', $value, $prefix);
}
/* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
if ($this->prefix !== null && stripos($url, $prefix) === false) {
return false;
}
@@ -78,7 +78,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
protected function call($method): bool
{
$this->setCallback($this->controller . '@' . $method);
$this->setCallback([$this->controller, $method]);
return true;
}
@@ -115,32 +115,32 @@ class RouteResource extends LoadableRoute implements IControllerRoute
$method = $request->getMethod();
// Delete
if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
if ($method === Request::REQUEST_TYPE_DELETE && $id !== null) {
return $this->call($this->methodNames['destroy']);
}
// Update
if ($id !== null && \in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], true) === true) {
if ($id !== null && \in_array($method, [Request::REQUEST_TYPE_PATCH, Request::REQUEST_TYPE_PUT], true) === true) {
return $this->call($this->methodNames['update']);
}
// Edit
if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
if ($method === Request::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
return $this->call($this->methodNames['edit']);
}
// Create
if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
if ($method === Request::REQUEST_TYPE_GET && $id === 'create') {
return $this->call($this->methodNames['create']);
}
// Save
if ($method === static::REQUEST_TYPE_POST) {
if ($method === Request::REQUEST_TYPE_POST) {
return $this->call($this->methodNames['store']);
}
// Show
if ($method === static::REQUEST_TYPE_GET && $id !== null) {
if ($method === Request::REQUEST_TYPE_GET && $id !== null) {
return $this->call($this->methodNames['show']);
}
+2 -2
View File
@@ -305,8 +305,8 @@ class Router
* Start the routing
*
* @return string|null
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws NotFoundHttpException
* @throws TokenMismatchException
* @throws HttpException
* @throws \Exception
*/
+24 -23
View File
@@ -12,7 +12,6 @@ namespace Pecee\SimpleRouter;
use DI\Container;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response;
@@ -76,7 +75,6 @@ class SimpleRouter
ob_start();
static::router()->setDebugEnabled(true)->start();
$routerOutput = ob_get_clean();
ob_end_clean();
} catch (\Exception $e) {
}
@@ -178,79 +176,79 @@ class SimpleRouter
* Route the given url to your callback on GET request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
*
* @return RouteUrl
*/
public static function get(string $url, $callback, array $settings = null): IRoute
{
return static::match(['get'], $url, $callback, $settings);
return static::match([Request::REQUEST_TYPE_GET], $url, $callback, $settings);
}
/**
* Route the given url to your callback on POST request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function post(string $url, $callback, array $settings = null): IRoute
{
return static::match(['post'], $url, $callback, $settings);
return static::match([Request::REQUEST_TYPE_POST], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PUT request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function put(string $url, $callback, array $settings = null): IRoute
{
return static::match(['put'], $url, $callback, $settings);
return static::match([Request::REQUEST_TYPE_PUT], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PATCH request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function patch(string $url, $callback, array $settings = null): IRoute
{
return static::match(['patch'], $url, $callback, $settings);
return static::match([Request::REQUEST_TYPE_PATCH], $url, $callback, $settings);
}
/**
* Route the given url to your callback on OPTIONS request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function options(string $url, $callback, array $settings = null): IRoute
{
return static::match(['options'], $url, $callback, $settings);
return static::match([Request::REQUEST_TYPE_OPTIONS], $url, $callback, $settings);
}
/**
* Route the given url to your callback on DELETE request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function delete(string $url, $callback, array $settings = null): IRoute
{
return static::match(['delete'], $url, $callback, $settings);
return static::match([Request::REQUEST_TYPE_DELETE], $url, $callback, $settings);
}
/**
@@ -307,14 +305,14 @@ class SimpleRouter
* Alias for the form method
*
* @param string $url
* @param callable $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
*/
public static function basic(string $url, $callback, array $settings = null): IRoute
{
return static::match(['get', 'post'], $url, $callback, $settings);
return static::form($url, $callback, $settings);
}
/**
@@ -322,14 +320,17 @@ class SimpleRouter
* Route the given url to your callback on POST and GET request method.
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
*/
public static function form(string $url, $callback, array $settings = null): IRoute
{
return static::match(['get', 'post'], $url, $callback, $settings);
return static::match([
Request::REQUEST_TYPE_GET,
Request::REQUEST_TYPE_POST
], $url, $callback, $settings);
}
/**
@@ -337,7 +338,7 @@ class SimpleRouter
*
* @param array $requestMethods
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
*/
@@ -358,7 +359,7 @@ class SimpleRouter
* This type will route the given url to your callback and allow any type of request method
*
* @param string $url
* @param string|\Closure $callback
* @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
*/
@@ -382,7 +383,7 @@ class SimpleRouter
* @param array|null $settings
* @return RouteController|IRoute
*/
public static function controller(string $url, $controller, array $settings = null)
public static function controller(string $url, string $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route);
@@ -402,7 +403,7 @@ class SimpleRouter
* @param array|null $settings
* @return RouteResource|IRoute
*/
public static function resource(string $url, $controller, array $settings = null)
public static function resource(string $url, string $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route);
@@ -465,7 +466,7 @@ class SimpleRouter
/**
* Get the request
*
* @return \Pecee\Http\Request
* @return Request
*/
public static function request(): Request
{