Compare commits

..

6 Commits

Author SHA1 Message Date
Simon Sessingø 5dbfc3dbfe Merge pull request #639 from skipperbent/v5-development
Version 5.1.0.0
2023-03-25 03:19:13 +01:00
Simon Sessingø 0aea8673d9 Merge pull request #632 from skipperbent/v5-development
Version 5.0.0.3
2023-02-13 14:06:24 +01:00
Simon Sessingø 9c66a4dfd8 Merge pull request #630 from skipperbent/v5-development
Version 5.0.0.2
2023-02-11 17:34:48 +01:00
Simon Sessingø d5bf77cbd4 Merge pull request #628 from skipperbent/v5-development
Fixed offsetGet return type deprication warning
2023-02-09 03:34:48 +01:00
Simon Sessingø 1e9fa9c6a1 Merge pull request #627 from skipperbent/v4-development
Version 5.0.0.0
2023-02-09 03:07:54 +01:00
Simon Sessingø 0630569f56 Merge pull request #592 from skipperbent/master
fixed json_encode 2nd parameter int flag issue in response and issue with offsetGet return type incompatibility
2023-02-09 02:30:02 +01:00
27 changed files with 194 additions and 240 deletions
+4 -16
View File
@@ -85,7 +85,7 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Registering new event](#registering-new-event) - [Registering new event](#registering-new-event)
- [Custom EventHandlers](#custom-eventhandlers) - [Custom EventHandlers](#custom-eventhandlers)
- [Advanced](#advanced) - [Advanced](#advanced)
- [Multiple route rendering](#multiple-route-rendering) - [Disable multiple route rendering](#disable-multiple-route-rendering)
- [Restrict access to IP](#restrict-access-to-ip) - [Restrict access to IP](#restrict-access-to-ip)
- [Setting custom base path](#setting-custom-base-path) - [Setting custom base path](#setting-custom-base-path)
- [Url rewriting](#url-rewriting) - [Url rewriting](#url-rewriting)
@@ -1036,17 +1036,6 @@ class CustomExceptionHandler implements IExceptionHandler
return; return;
} }
/* Other error */
if($error instanceof MyCustomException) {
$request->setRewriteRoute(
// Add new route based on current url (minus query-string) and add custom parameters.
(new RouteUrl(url(null, null, []), 'PageController@error'))->setParameters(['exception' => $error])
);
return;
}
throw $error; throw $error;
@@ -1503,12 +1492,11 @@ class DatabaseDebugHandler implements IEventHandler
# Advanced # Advanced
## Multiple route rendering ## Disable multiple route rendering
If you need multiple routes to be executed on the same url, you can enable this feature by setting `SimpleRouter::enableMultiRouteRendering(true)` By default the router will try to execute all routes that matches a given url. To stop the router from executing any further routes any method can return a value.
in your `routes.php` file.
This is most commonly used in advanced cases, for example in CMS systems where multiple routes needs to be rendered. This behavior can be easily disabled by setting `SimpleRouter::enableMultiRouteRendering(false)` in your `routes.php` file. This is the same behavior as version 3 and below.
## Restrict access to IP ## Restrict access to IP
+11 -11
View File
@@ -9,37 +9,37 @@ class InputFile implements IInputItem
/** /**
* @var string * @var string
*/ */
public string $index; public $index;
/** /**
* @var string * @var string
*/ */
public string $name; public $name;
/** /**
* @var string|null * @var string|null
*/ */
public ?string $filename = null; public $filename;
/** /**
* @var int|null * @var int|null
*/ */
public ?int $size = null; public $size;
/** /**
* @var string|null * @var int|null
*/ */
public ?string $type = null; public $type;
/** /**
* @var int * @var int
*/ */
public int $errors = 0; public $errors;
/** /**
* @var string|null * @var string|null
*/ */
public ?string $tmpName = null; public $tmpName;
public function __construct(string $index) public function __construct(string $index)
{ {
@@ -74,7 +74,7 @@ class InputFile implements IInputItem
'error' => null, 'error' => null,
]; ];
return (new self($values['index'])) return (new static($values['index']))
->setSize((int)$values['size']) ->setSize((int)$values['size'])
->setError((int)$values['error']) ->setError((int)$values['error'])
->setType($values['type']) ->setType($values['type'])
@@ -104,9 +104,9 @@ class InputFile implements IInputItem
} }
/** /**
* @return int * @return string
*/ */
public function getSize(): ?int public function getSize(): string
{ {
return $this->size; return $this->size;
} }
+7 -7
View File
@@ -10,40 +10,40 @@ class InputHandler
/** /**
* @var array * @var array
*/ */
protected array $get = []; protected $get = [];
/** /**
* @var array * @var array
*/ */
protected array $post = []; protected $post = [];
/** /**
* @var array * @var array
*/ */
protected array $file = []; protected $file = [];
/** /**
* @var Request * @var Request
*/ */
protected Request $request; protected $request;
/** /**
* Original post variables * Original post variables
* @var array * @var array
*/ */
protected array $originalPost = []; protected $originalPost = [];
/** /**
* Original get/params variables * Original get/params variables
* @var array * @var array
*/ */
protected array $originalParams = []; protected $originalParams = [];
/** /**
* Get original file variables * Get original file variables
* @var array * @var array
*/ */
protected array $originalFile = []; protected $originalFile = [];
/** /**
* Input constructor. * Input constructor.
+2 -11
View File
@@ -8,18 +8,10 @@ use IteratorAggregate;
class InputItem implements ArrayAccess, IInputItem, IteratorAggregate class InputItem implements ArrayAccess, IInputItem, IteratorAggregate
{ {
public string $index; public $index;
public string $name; public $name;
/**
* @var mixed|null
*/
public $value; public $value;
/**
* @param string $index
* @param mixed $value
*/
public function __construct(string $index, $value = null) public function __construct(string $index, $value = null)
{ {
$this->index = $index; $this->index = $index;
@@ -89,7 +81,6 @@ class InputItem implements ArrayAccess, IInputItem, IteratorAggregate
return isset($this->value[$offset]); return isset($this->value[$offset]);
} }
#[\ReturnTypeWillChange]
public function offsetGet($offset): ?self public function offsetGet($offset): ?self
{ {
if ($this->offsetExists($offset) === true) { if ($this->offsetExists($offset) === true) {
+20 -25
View File
@@ -17,18 +17,18 @@ class BaseCsrfVerifier implements IMiddleware
* For example: /admin/* * For example: /admin/*
* @var array|null * @var array|null
*/ */
protected array $except = []; protected $except;
/** /**
* Urls to include. Can be used to include urls from a certain path. * Urls to include. Can be used to include urls from a certain path.
* @var array|null * @var array|null
*/ */
protected array $include = []; protected $include;
/** /**
* @var ITokenProvider * @var ITokenProvider
*/ */
protected ITokenProvider $tokenProvider; protected $tokenProvider;
/** /**
* BaseCsrfVerifier constructor. * BaseCsrfVerifier constructor.
@@ -38,23 +38,6 @@ class BaseCsrfVerifier implements IMiddleware
$this->tokenProvider = new CookieTokenProvider(); $this->tokenProvider = new CookieTokenProvider();
} }
protected function isIncluded(Request $request): bool
{
if (count($this->include) > 0) {
foreach ($this->include as $includeUrl) {
$includeUrl = rtrim($includeUrl, '/');
if ($includeUrl[strlen($includeUrl) - 1] === '*') {
$includeUrl = rtrim($includeUrl, '*');
return $request->getUrl()->contains($includeUrl);
}
return ($includeUrl === rtrim($request->getUrl()->getRelativeUrl(false), '/'));
}
}
return false;
}
/** /**
* Check if the url matches the urls in the except property * Check if the url matches the urls in the except property
* @param Request $request * @param Request $request
@@ -62,11 +45,11 @@ class BaseCsrfVerifier implements IMiddleware
*/ */
protected function skip(Request $request): bool protected function skip(Request $request): bool
{ {
if (count($this->except) === 0) { if ($this->except === null || count($this->except) === 0) {
return false; return false;
} }
foreach ($this->except as $url) { foreach($this->except as $url) {
$url = rtrim($url, '/'); $url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') { if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*'); $url = rtrim($url, '*');
@@ -77,9 +60,20 @@ class BaseCsrfVerifier implements IMiddleware
if ($skip === true) { if ($skip === true) {
$skip = !$this->isIncluded($request); if(is_array($this->include) === true && count($this->include) > 0) {
foreach($this->include as $includeUrl) {
$includeUrl = rtrim($includeUrl, '/');
if ($includeUrl[strlen($includeUrl) - 1] === '*') {
$includeUrl = rtrim($includeUrl, '*');
$skip = !$request->getUrl()->contains($includeUrl);
break;
}
if ($skip === false) { $skip = !($includeUrl === rtrim($request->getUrl()->getRelativeUrl(false), '/'));
}
}
if($skip === false) {
continue; continue;
} }
@@ -98,11 +92,12 @@ class BaseCsrfVerifier implements IMiddleware
*/ */
public function handle(Request $request): void public function handle(Request $request): void
{ {
if ($this->skip($request) === false && ($request->isPostBack() === true || $this->isIncluded($request) === true)) { if ($this->skip($request) === false && $request->isPostBack() === true) {
$token = $request->getInputHandler()->value( $token = $request->getInputHandler()->value(
static::POST_KEY, static::POST_KEY,
$request->getHeader(static::HEADER_KEY), $request->getHeader(static::HEADER_KEY),
Request::$requestTypesPost
); );
if ($this->tokenProvider->validate((string)$token) === false) { if ($this->tokenProvider->validate((string)$token) === false) {
@@ -7,8 +7,8 @@ use Pecee\SimpleRouter\Exceptions\HttpException;
abstract class IpRestrictAccess implements IMiddleware abstract class IpRestrictAccess implements IMiddleware
{ {
protected array $ipBlacklist = []; protected $ipBlacklist = [];
protected array $ipWhitelist = []; protected $ipWhitelist = [];
protected function validate(string $ip): bool protected function validate(string $ip): bool
{ {
+17 -19
View File
@@ -29,7 +29,7 @@ class Request
* All request-types * All request-types
* @var string[] * @var string[]
*/ */
public static array $requestTypes = [ public static $requestTypes = [
self::REQUEST_TYPE_GET, self::REQUEST_TYPE_GET,
self::REQUEST_TYPE_POST, self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT, self::REQUEST_TYPE_PUT,
@@ -43,7 +43,7 @@ class Request
* Post request-types. * Post request-types.
* @var string[] * @var string[]
*/ */
public static array $requestTypesPost = [ public static $requestTypesPost = [
self::REQUEST_TYPE_POST, self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT, self::REQUEST_TYPE_PUT,
self::REQUEST_TYPE_PATCH, self::REQUEST_TYPE_PATCH,
@@ -55,65 +55,65 @@ class Request
* *
* @var array * @var array
*/ */
private array $data = []; private $data = [];
/** /**
* Server headers * Server headers
* @var array * @var array
*/ */
protected array $headers = []; protected $headers = [];
/** /**
* Request ContentType * Request ContentType
* @var string * @var string
*/ */
protected string $contentType; protected $contentType;
/** /**
* Request host * Request host
* @var string|null * @var string
*/ */
protected ?string $host; protected $host;
/** /**
* Current request url * Current request url
* @var Url * @var Url
*/ */
protected Url $url; protected $url;
/** /**
* Request method * Request method
* @var string * @var string
*/ */
protected string $method; protected $method;
/** /**
* Input handler * Input handler
* @var InputHandler * @var InputHandler
*/ */
protected InputHandler $inputHandler; protected $inputHandler;
/** /**
* Defines if request has pending rewrite * Defines if request has pending rewrite
* @var bool * @var bool
*/ */
protected bool $hasPendingRewrite = false; protected $hasPendingRewrite = false;
/** /**
* @var ILoadableRoute|null * @var ILoadableRoute|null
*/ */
protected ?ILoadableRoute $rewriteRoute = null; protected $rewriteRoute;
/** /**
* Rewrite url * Rewrite url
* @var string|null * @var string|null
*/ */
protected ?string $rewriteUrl = null; protected $rewriteUrl;
/** /**
* @var array * @var array
*/ */
protected array $loadedRoutes = []; protected $loadedRoutes = [];
/** /**
* Request constructor. * Request constructor.
@@ -224,17 +224,15 @@ class Request
*/ */
public function getIp(bool $safeMode = false): ?string public function getIp(bool $safeMode = false): ?string
{ {
$headers = []; $headers = ['remote-addr'];
if($safeMode === false) { if($safeMode === false) {
$headers = [ $headers = array_merge($headers, [
'http-cf-connecting-ip', 'http-cf-connecting-ip',
'http-client-ip', 'http-client-ip',
'http-x-forwarded-for', 'http-x-forwarded-for',
]; ]);
} }
$headers[] = 'remote-addr';
return $this->getFirstHeader($headers); return $this->getFirstHeader($headers);
} }
+2 -1
View File
@@ -7,7 +7,7 @@ use Pecee\Exceptions\InvalidArgumentException;
class Response class Response
{ {
protected Request $request; protected $request;
public function __construct(Request $request) public function __construct(Request $request)
{ {
@@ -65,6 +65,7 @@ class Response
public function cache(string $eTag, int $lastModifiedTime = 2592000): self public function cache(string $eTag, int $lastModifiedTime = 2592000): self
{ {
$this->headers([ $this->headers([
'Cache-Control: public', 'Cache-Control: public',
sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)), sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)),
@@ -12,12 +12,12 @@ class CookieTokenProvider implements ITokenProvider
/** /**
* @var string * @var string
*/ */
protected ?string $token = null; protected $token;
/** /**
* @var int * @var int
*/ */
protected int $cookieTimeoutMinutes = 120; protected $cookieTimeoutMinutes = 120;
/** /**
* CookieTokenProvider constructor. * CookieTokenProvider constructor.
+10 -10
View File
@@ -10,53 +10,53 @@ class Url implements JsonSerializable
/** /**
* @var string|null * @var string|null
*/ */
private ?string $originalUrl = null; private $originalUrl;
/** /**
* @var string|null * @var string|null
*/ */
private ?string $scheme = null; private $scheme;
/** /**
* @var string|null * @var string|null
*/ */
private ?string $host = null; private $host;
/** /**
* @var int|null * @var int|null
*/ */
private ?int $port = null; private $port;
/** /**
* @var string|null * @var string|null
*/ */
private ?string $username = null; private $username;
/** /**
* @var string|null * @var string|null
*/ */
private ?string $password = null; private $password;
/** /**
* @var string|null * @var string|null
*/ */
private ?string $path = null; private $path;
/** /**
* Original path with no sanitization to ending slash * Original path with no sanitization to ending slash
* @var string|null * @var string|null
*/ */
private ?string $originalPath = null; private $originalPath;
/** /**
* @var array * @var array
*/ */
private array $params = []; private $params = [];
/** /**
* @var string|null * @var string|null
*/ */
private ?string $fragment = null; private $fragment;
/** /**
* Url constructor. * Url constructor.
@@ -27,11 +27,11 @@ class ClassLoader implements IClassLoader
* @param object $class * @param object $class
* @param string $method * @param string $method
* @param array $parameters * @param array $parameters
* @return string * @return object
*/ */
public function loadClassMethod($class, string $method, array $parameters): string public function loadClassMethod($class, string $method, array $parameters)
{ {
return (string)call_user_func_array([$class, $method], array_values($parameters)); return call_user_func_array([$class, $method], array_values($parameters));
} }
/** /**
@@ -39,11 +39,11 @@ class ClassLoader implements IClassLoader
* *
* @param Callable $closure * @param Callable $closure
* @param array $parameters * @param array $parameters
* @return string * @return mixed
*/ */
public function loadClosure(callable $closure, array $parameters): string public function loadClosure(Callable $closure, array $parameters)
{ {
return (string)call_user_func_array($closure, array_values($parameters)); return call_user_func_array($closure, array_values($parameters));
} }
} }
@@ -17,7 +17,7 @@ interface IClassLoader
* @param object $class * @param object $class
* @param string $method * @param string $method
* @param array $parameters * @param array $parameters
* @return mixed * @return object
*/ */
public function loadClassMethod($class, string $method, array $parameters); public function loadClassMethod($class, string $method, array $parameters);
@@ -12,17 +12,17 @@ class EventArgument implements IEventArgument
* Event name * Event name
* @var string * @var string
*/ */
protected string $eventName; protected $eventName;
/** /**
* @var Router * @var Router
*/ */
protected Router $router; protected $router;
/** /**
* @var array * @var array
*/ */
protected array $arguments = []; protected $arguments = [];
public function __construct(string $eventName, Router $router, array $arguments = []) public function __construct(string $eventName, Router $router, array $arguments = [])
{ {
@@ -9,12 +9,12 @@ class ClassNotFoundHttpException extends NotFoundHttpException
/** /**
* @var string * @var string
*/ */
protected string $class; protected $class;
/** /**
* @var string|null * @var string|null
*/ */
protected ?string $method = null; protected $method;
public function __construct(string $class, ?string $method = null, string $message = "", int $code = 0, Throwable $previous = null) public function __construct(string $class, ?string $method = null, string $message = "", int $code = 0, Throwable $previous = null)
{ {
@@ -20,7 +20,7 @@ class CallbackExceptionHandler implements IExceptionHandler
/** /**
* @var Closure * @var Closure
*/ */
protected Closure $callback; protected $callback;
public function __construct(Closure $callback) public function __construct(Closure $callback)
{ {
@@ -13,7 +13,7 @@ class DebugEventHandler implements IEventHandler
* Debug callback * Debug callback
* @var Closure * @var Closure
*/ */
protected Closure $callback; protected $callback;
public function __construct() public function __construct()
{ {
@@ -97,7 +97,7 @@ class EventHandler implements IEventHandler
* All available events * All available events
* @var array * @var array
*/ */
public static array $events = [ public static $events = [
self::EVENT_ALL, self::EVENT_ALL,
self::EVENT_INIT, self::EVENT_INIT,
self::EVENT_LOAD, self::EVENT_LOAD,
@@ -120,7 +120,7 @@ class EventHandler implements IEventHandler
* List of all registered events * List of all registered events
* @var array * @var array
*/ */
private array $registeredEvents = []; private $registeredEvents = [];
/** /**
* Register new event * Register new event
@@ -12,17 +12,17 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
/** /**
* @var string * @var string
*/ */
protected string $url; protected $url;
/** /**
* @var string * @var string
*/ */
protected ?string $name = null; protected $name;
/** /**
* @var string|null * @var string|null
*/ */
protected ?string $regex = null; protected $regex;
/** /**
* Loads and renders middlewares-classes * Loads and renders middlewares-classes
@@ -195,7 +195,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*/ */
public function hasName(string $name): bool public function hasName(string $name): bool
{ {
return strtolower((string)$this->name) === strtolower($name); return strtolower((string)$this->name) === strtolower((string)$name);
} }
/** /**
+15 -15
View File
@@ -18,37 +18,37 @@ abstract class Route implements IRoute
* *
* @var bool * @var bool
*/ */
protected bool $filterEmptyParams = true; protected $filterEmptyParams = true;
/** /**
* If true the last parameter of the route will include ending trail/slash. * If true the last parameter of the route will include ending trail/slash.
* @var bool * @var bool
*/ */
protected bool $slashParameterEnabled = false; protected $slashParameterEnabled = false;
/** /**
* Default regular expression used for parsing parameters. * Default regular expression used for parsing parameters.
* @var string|null * @var string|null
*/ */
protected ?string $defaultParameterRegex = null; protected $defaultParameterRegex;
protected string $paramModifiers = '{}'; protected $paramModifiers = '{}';
protected string $paramOptionalSymbol = '?'; protected $paramOptionalSymbol = '?';
protected string $urlRegex = '/^%s\/?$/u'; protected $urlRegex = '/^%s\/?$/u';
protected ?IGroupRoute $group = null; protected $group;
protected ?IRoute $parent = null; protected $parent;
/** /**
* @var string|callable|null * @var string|callable|null
*/ */
protected $callback; protected $callback;
protected ?string $defaultNamespace = null; protected $defaultNamespace;
/* Default options */ /* Default options */
protected ?string $namespace = null; protected $namespace;
protected array $requestMethods = []; protected $requestMethods = [];
protected array $where = []; protected $where = [];
protected array $parameters = []; protected $parameters = [];
protected array $originalParameters = []; protected $originalParameters = [];
protected array $middlewares = []; protected $middlewares = [];
/** /**
* Render route * Render route
@@ -6,10 +6,10 @@ use Pecee\Http\Request;
class RouteController extends LoadableRoute implements IControllerRoute class RouteController extends LoadableRoute implements IControllerRoute
{ {
protected string $defaultMethod = 'index'; protected $defaultMethod = 'index';
protected string $controller; protected $controller;
protected ?string $method = null; protected $method;
protected array $names = []; protected $names = [];
public function __construct($url, $controller) public function __construct($url, $controller)
{ {
+7 -7
View File
@@ -7,12 +7,12 @@ use Pecee\SimpleRouter\Handlers\IExceptionHandler;
class RouteGroup extends Route implements IGroupRoute class RouteGroup extends Route implements IGroupRoute
{ {
protected string $urlRegex = '/^%s\/?/u'; protected $urlRegex = '/^%s\/?/u';
protected ?string $prefix = null; protected $prefix;
protected ?string $name = null; protected $name;
protected array $domains = []; protected $domains = [];
protected array $exceptionHandlers = []; protected $exceptionHandlers = [];
protected bool $mergeExceptionHandlers = true; protected $mergeExceptionHandlers = true;
/** /**
* Method called to check if a domain matches * Method called to check if a domain matches
@@ -22,7 +22,7 @@ class RouteGroup extends Route implements IGroupRoute
*/ */
public function matchDomain(Request $request): bool public function matchDomain(Request $request): bool
{ {
if (count($this->domains) === 0) { if ($this->domains === null || count($this->domains) === 0) {
return true; return true;
} }
+26 -29
View File
@@ -6,28 +6,28 @@ use Pecee\Http\Request;
class RouteResource extends LoadableRoute implements IControllerRoute class RouteResource extends LoadableRoute implements IControllerRoute
{ {
protected array $urls = [ protected $urls = [
'index' => '', 'index' => '',
'create' => 'create', 'create' => 'create',
'store' => '', 'store' => '',
'show' => '', 'show' => '',
'edit' => 'edit', 'edit' => 'edit',
'update' => '', 'update' => '',
'destroy' => '', 'destroy' => '',
]; ];
protected array $methodNames = [ protected $methodNames = [
'index' => 'index', 'index' => 'index',
'create' => 'create', 'create' => 'create',
'store' => 'store', 'store' => 'store',
'show' => 'show', 'show' => 'show',
'edit' => 'edit', 'edit' => 'edit',
'update' => 'update', 'update' => 'update',
'destroy' => 'destroy', 'destroy' => 'destroy',
]; ];
protected array $names = []; protected $names = [];
protected string $controller; protected $controller;
public function __construct($url, $controller) public function __construct($url, $controller)
{ {
@@ -68,15 +68,12 @@ class RouteResource extends LoadableRoute implements IControllerRoute
*/ */
public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string
{ {
$url = parent::findUrl($method, $parameters, $name); $url = array_search($name, $this->names, true);
if ($url !== false) {
$action = array_search($name, $this->names, true); return rtrim($this->url . $this->urls[$url], '/') . '/';
if ($action !== false) {
return $url . $this->urls[$action];
} }
return $url; return $this->url;
} }
protected function call($method): bool protected function call($method): bool
@@ -175,12 +172,12 @@ class RouteResource extends LoadableRoute implements IControllerRoute
$this->name = $name; $this->name = $name;
$this->names = [ $this->names = [
'index' => $this->name . '.index', 'index' => $this->name . '.index',
'create' => $this->name . '.create', 'create' => $this->name . '.create',
'store' => $this->name . '.store', 'store' => $this->name . '.store',
'show' => $this->name . '.show', 'show' => $this->name . '.show',
'edit' => $this->name . '.edit', 'edit' => $this->name . '.edit',
'update' => $this->name . '.update', 'update' => $this->name . '.update',
'destroy' => $this->name . '.destroy', 'destroy' => $this->name . '.destroy',
]; ];
+36 -36
View File
@@ -28,56 +28,56 @@ class Router
* Current request * Current request
* @var Request * @var Request
*/ */
protected Request $request; protected $request;
/** /**
* Defines if a route is currently being processed. * Defines if a route is currently being processed.
* @var bool * @var bool
*/ */
protected bool $isProcessingRoute; protected $isProcessingRoute;
/** /**
* Defines all data from current processing route. * Defines all data from current processing route.
* @var ILoadableRoute * @var ILoadableRoute
*/ */
protected ILoadableRoute $currentProcessingRoute; protected $currentProcessingRoute;
/** /**
* All added routes * All added routes
* @var array * @var array
*/ */
protected array $routes = []; protected $routes = [];
/** /**
* List of processed routes * List of processed routes
* @var array|ILoadableRoute[] * @var array|ILoadableRoute[]
*/ */
protected array $processedRoutes = []; protected $processedRoutes = [];
/** /**
* Stack of routes used to keep track of sub-routes added * Stack of routes used to keep track of sub-routes added
* when a route is being processed. * when a route is being processed.
* @var array * @var array
*/ */
protected array $routeStack = []; protected $routeStack = [];
/** /**
* List of added bootmanagers * List of added bootmanagers
* @var array * @var array
*/ */
protected array $bootManagers = []; protected $bootManagers = [];
/** /**
* Csrf verifier class * Csrf verifier class
* @var BaseCsrfVerifier|null * @var BaseCsrfVerifier|null
*/ */
protected ?BaseCsrfVerifier $csrfVerifier; protected $csrfVerifier;
/** /**
* Get exception handlers * Get exception handlers
* @var array * @var array
*/ */
protected array $exceptionHandlers = []; protected $exceptionHandlers = [];
/** /**
* List of loaded exception that has been loaded. * List of loaded exception that has been loaded.
@@ -85,44 +85,44 @@ class Router
* *
* @var array * @var array
*/ */
protected array $loadedExceptionHandlers = []; protected $loadedExceptionHandlers = [];
/** /**
* Enable or disabled debugging * Enable or disabled debugging
* @var bool * @var bool
*/ */
protected bool $debugEnabled = false; protected $debugEnabled = false;
/** /**
* The start time used when debugging is enabled * The start time used when debugging is enabled
* @var float * @var float
*/ */
protected float $debugStartTime; protected $debugStartTime;
/** /**
* List containing all debug messages * List containing all debug messages
* @var array * @var array
*/ */
protected array $debugList = []; protected $debugList = [];
/** /**
* Contains any registered event-handler. * Contains any registered event-handler.
* @var array * @var array
*/ */
protected array $eventHandlers = []; protected $eventHandlers = [];
/** /**
* Class loader instance * Class loader instance
* @var IClassLoader * @var IClassLoader
*/ */
protected IClassLoader $classLoader; protected $classLoader;
/** /**
* When enabled the router will render all routes that matches. * When enabled the router will render all routes that matches.
* When disabled the router will stop execution when first route is found. * When disabled the router will stop execution when first route is found.
* @var bool * @var bool
*/ */
protected bool $renderMultipleRoutes = false; protected $renderMultipleRoutes = true;
/** /**
* Router constructor. * Router constructor.
@@ -166,7 +166,7 @@ class Router
public function addRoute(IRoute $route): IRoute public function addRoute(IRoute $route): IRoute
{ {
$this->fireEvents(EventHandler::EVENT_ADD_ROUTE, [ $this->fireEvents(EventHandler::EVENT_ADD_ROUTE, [
'route' => $route, 'route' => $route,
'isSubRoute' => $this->isProcessingRoute, 'isSubRoute' => $this->isProcessingRoute,
]); ]);
@@ -307,7 +307,7 @@ class Router
$this->debug('Rendering bootmanager "%s"', $className); $this->debug('Rendering bootmanager "%s"', $className);
$this->fireEvents(EventHandler::EVENT_RENDER_BOOTMANAGER, [ $this->fireEvents(EventHandler::EVENT_RENDER_BOOTMANAGER, [
'bootmanagers' => $this->bootManagers, 'bootmanagers' => $this->bootManagers,
'bootmanager' => $manager, 'bootmanager' => $manager,
]); ]);
/* Render bootmanager */ /* Render bootmanager */
@@ -345,8 +345,8 @@ class Router
try { try {
/* Verify csrf token for request */ /* Verify csrf token for request */
$this->csrfVerifier->handle($this->request); $this->csrfVerifier->handle($this->request);
} catch (Exception $e) { } catch(\Exception $e) {
return $this->handleException($e); $this->handleException($e);
} }
} }
@@ -381,7 +381,7 @@ class Router
foreach ($this->processedRoutes as $key => $route) { foreach ($this->processedRoutes as $key => $route) {
$this->debug('Matching route "%s"', get_class($route)); $this->debug('Matching route "%s"', get_class($route));
/* Add current processing route to constants */ /* Add current processing route to constants */
$this->currentProcessingRoute = $route; $this->currentProcessingRoute = $route;
@@ -405,7 +405,7 @@ class Router
} }
$this->fireEvents(EventHandler::EVENT_RENDER_MIDDLEWARES, [ $this->fireEvents(EventHandler::EVENT_RENDER_MIDDLEWARES, [
'route' => $route, 'route' => $route,
'middlewares' => $route->getMiddlewares(), 'middlewares' => $route->getMiddlewares(),
]); ]);
@@ -427,7 +427,7 @@ class Router
$routeOutput = $route->renderRoute($this->request, $this); $routeOutput = $route->renderRoute($this->request, $this);
if ($this->renderMultipleRoutes === true) { if ($this->renderMultipleRoutes === true) {
if ($routeOutput !== '') { if ($routeOutput !== null) {
return $routeOutput; return $routeOutput;
} }
@@ -444,12 +444,12 @@ class Router
} }
} catch (Exception $e) { } catch (Exception $e) {
return $this->handleException($e); $this->handleException($e);
} }
if ($methodNotAllowed === true) { if ($methodNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod()); $message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod());
return $this->handleException(new NotFoundHttpException($message, 403)); $this->handleException(new NotFoundHttpException($message, 403));
} }
if (count($this->request->getLoadedRoutes()) === 0) { if (count($this->request->getLoadedRoutes()) === 0) {
@@ -500,7 +500,7 @@ class Router
$this->request->setHasPendingRewrite(false); $this->request->setHasPendingRewrite(false);
$this->fireEvents(EventHandler::EVENT_REWRITE, [ $this->fireEvents(EventHandler::EVENT_REWRITE, [
'rewriteUrl' => $this->request->getRewriteUrl(), 'rewriteUrl' => $this->request->getRewriteUrl(),
'rewriteRoute' => $this->request->getRewriteRoute(), 'rewriteRoute' => $this->request->getRewriteRoute(),
]); ]);
@@ -521,7 +521,7 @@ class Router
$this->debug('Starting exception handling for "%s"', get_class($e)); $this->debug('Starting exception handling for "%s"', get_class($e));
$this->fireEvents(EventHandler::EVENT_LOAD_EXCEPTIONS, [ $this->fireEvents(EventHandler::EVENT_LOAD_EXCEPTIONS, [
'exception' => $e, 'exception' => $e,
'exceptionHandlers' => $this->exceptionHandlers, 'exceptionHandlers' => $this->exceptionHandlers,
]); ]);
@@ -533,8 +533,8 @@ class Router
} }
$this->fireEvents(EventHandler::EVENT_RENDER_EXCEPTION, [ $this->fireEvents(EventHandler::EVENT_RENDER_EXCEPTION, [
'exception' => $e, 'exception' => $e,
'exceptionHandler' => $handler, 'exceptionHandler' => $handler,
'exceptionHandlers' => $this->exceptionHandlers, 'exceptionHandlers' => $this->exceptionHandlers,
]); ]);
@@ -556,7 +556,7 @@ class Router
$this->debug('Exception handler contains rewrite, reloading routes'); $this->debug('Exception handler contains rewrite, reloading routes');
$this->fireEvents(EventHandler::EVENT_REWRITE, [ $this->fireEvents(EventHandler::EVENT_REWRITE, [
'rewriteUrl' => $this->request->getRewriteUrl(), 'rewriteUrl' => $this->request->getRewriteUrl(),
'rewriteRoute' => $this->request->getRewriteRoute(), 'rewriteRoute' => $this->request->getRewriteRoute(),
]); ]);
@@ -667,9 +667,9 @@ class Router
$this->debug('Finding url', func_get_args()); $this->debug('Finding url', func_get_args());
$this->fireEvents(EventHandler::EVENT_GET_URL, [ $this->fireEvents(EventHandler::EVENT_GET_URL, [
'name' => $name, 'name' => $name,
'parameters' => $parameters, 'parameters' => $parameters,
'getParams' => $getParams, 'getParams' => $getParams,
]); ]);
if ($name === '' && $parameters === '') { if ($name === '' && $parameters === '') {
@@ -913,8 +913,8 @@ class Router
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$this->debugList[] = [ $this->debugList[] = [
'message' => vsprintf($message, $args), 'message' => vsprintf($message, $args),
'time' => number_format(microtime(true) - $this->debugStartTime, 10), 'time' => number_format(microtime(true) - $this->debugStartTime, 10),
'trace' => end($trace), 'trace' => end($trace),
]; ];
} }
@@ -940,7 +940,7 @@ class Router
{ {
return $this->debugList; return $this->debugList;
} }
/** /**
* Get the current processing route details. * Get the current processing route details.
* *
+5 -5
View File
@@ -37,19 +37,19 @@ class SimpleRouter
* Default namespace added to all routes * Default namespace added to all routes
* @var string|null * @var string|null
*/ */
protected static ?string $defaultNamespace = null; protected static $defaultNamespace;
/** /**
* The response object * The response object
* @var Response|null * @var Response
*/ */
protected static ?Response $response = null; protected static $response;
/** /**
* Router instance * Router instance
* @var Router * @var Router
*/ */
protected static ?Router $router = null; protected static $router;
/** /**
* Start routing * Start routing
@@ -493,7 +493,7 @@ class SimpleRouter
* Prepends the default namespace to all new routes added. * Prepends the default namespace to all new routes added.
* *
* @param ILoadableRoute|IRoute $route * @param ILoadableRoute|IRoute $route
* @return IRoute|ILoadableRoute * @return IRoute
*/ */
public static function addDefaultNamespace(IRoute $route): IRoute public static function addDefaultNamespace(IRoute $route): IRoute
{ {
@@ -2,12 +2,12 @@
class DummyCsrfVerifier extends \Pecee\Http\Middleware\BaseCsrfVerifier { class DummyCsrfVerifier extends \Pecee\Http\Middleware\BaseCsrfVerifier {
protected array $except = [ protected $except = [
'/exclude-page', '/exclude-page',
'/exclude-all/*', '/exclude-all/*',
]; ];
protected array $include = [ protected $include = [
'/exclude-all/include-page', '/exclude-all/include-page',
]; ];
@@ -2,12 +2,12 @@
class IpRestrictMiddleware extends \Pecee\Http\Middleware\IpRestrictAccess { class IpRestrictMiddleware extends \Pecee\Http\Middleware\IpRestrictAccess {
protected array $ipBlacklist = [ protected $ipBlacklist = [
'5.5.5.5', '5.5.5.5',
'8.8.*', '8.8.*',
]; ];
protected array $ipWhitelist = [ protected $ipWhitelist = [
'8.8.2.2', '8.8.2.2',
]; ];
@@ -66,20 +66,4 @@ class RouterResourceTest extends \PHPUnit\Framework\TestCase
} }
public function testResourceUrls()
{
TestRouter::resource('/resource', 'ResourceController')->name('resource');
TestRouter::debugOutputNoReset('/resource');
$this->assertEquals('/resource/3/create/', TestRouter::router()->getUrl('resource.create', ['id' => 3]));
$this->assertEquals('/resource/3/edit/', TestRouter::router()->getUrl('resource.edit', ['id' => 3]));
$this->assertEquals('/resource/3/', TestRouter::router()->getUrl('resource.update', ['id' => 3]));
$this->assertEquals('/resource/3/', TestRouter::router()->getUrl('resource.destroy', ['id' => 3]));
$this->assertEquals('/resource/3/', TestRouter::router()->getUrl('resource.delete', ['id' => 3]));
$this->assertEquals('/resource/', TestRouter::router()->getUrl('resource'));
TestRouter::router()->reset();
}
} }