[CLEANUP] Added qualifier import.

This commit is contained in:
Simon Sessingø
2021-03-29 15:40:50 +02:00
parent 8eba5ab3d5
commit d6bc713e5b
24 changed files with 145 additions and 123 deletions
@@ -2,7 +2,9 @@
namespace Pecee\Http\Exceptions; namespace Pecee\Http\Exceptions;
class MalformedUrlException extends \Exception use Exception;
class MalformedUrlException extends Exception
{ {
} }
+15 -15
View File
@@ -63,7 +63,7 @@ class InputHandler
public function parseInputs(): void public function parseInputs(): void
{ {
/* Parse get requests */ /* Parse get requests */
if (\count($_GET) !== 0) { if (count($_GET) !== 0) {
$this->originalParams = $_GET; $this->originalParams = $_GET;
$this->get = $this->parseInputItem($this->originalParams); $this->get = $this->parseInputItem($this->originalParams);
} }
@@ -85,12 +85,12 @@ class InputHandler
} }
} }
if (\count($this->originalPost) !== 0) { if (count($this->originalPost) !== 0) {
$this->post = $this->parseInputItem($this->originalPost); $this->post = $this->parseInputItem($this->originalPost);
} }
/* Parse get requests */ /* Parse get requests */
if (\count($_FILES) !== 0) { if (count($_FILES) !== 0) {
$this->originalFile = $_FILES; $this->originalFile = $_FILES;
$this->file = $this->parseFiles($this->originalFile); $this->file = $this->parseFiles($this->originalFile);
} }
@@ -108,13 +108,13 @@ class InputHandler
foreach ($files as $key => $value) { foreach ($files as $key => $value) {
// Parse multi dept file array // Parse multi dept file array
if(isset($value['name']) === false && \is_array($value) === true) { if(isset($value['name']) === false && is_array($value) === true) {
$list[$key] = $this->parseFiles($value, $key); $list[$key] = $this->parseFiles($value, $key);
continue; continue;
} }
// Handle array input // Handle array input
if (\is_array($value['name']) === false) { if (is_array($value['name']) === false) {
$values['index'] = $parentKey ?? $key; $values['index'] = $parentKey ?? $key;
try { try {
@@ -156,7 +156,7 @@ class InputHandler
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
if (\is_array($original['name'][$key]) === false) { if (is_array($original['name'][$key]) === false) {
try { try {
@@ -210,7 +210,7 @@ class InputHandler
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
// Handle array input // Handle array input
if (\is_array($value) === true) { if (is_array($value) === true) {
$value = $this->parseInputItem($value); $value = $this->parseInputItem($value);
} }
@@ -231,15 +231,15 @@ class InputHandler
{ {
$element = null; $element = null;
if (\count($methods) === 0 || \in_array(Request::REQUEST_TYPE_GET, $methods, true) === true) { if (count($methods) === 0 || in_array(Request::REQUEST_TYPE_GET, $methods, true) === true) {
$element = $this->get($index); $element = $this->get($index);
} }
if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array(Request::REQUEST_TYPE_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); $element = $this->post($index);
} }
if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array('file', $methods, true) === true)) { if (($element === null && count($methods) === 0) || (count($methods) !== 0 && in_array('file', $methods, true) === true)) {
$element = $this->file($index); $element = $this->file($index);
} }
@@ -256,7 +256,7 @@ class InputHandler
$item = $item->getValue(); $item = $item->getValue();
} }
$output[$key] = \is_array($item) ? $this->getValueFromArray($item) : $item; $output[$key] = is_array($item) ? $this->getValueFromArray($item) : $item;
} }
return $output; return $output;
@@ -279,13 +279,13 @@ class InputHandler
} }
/* Handle collection */ /* Handle collection */
if (\is_array($input) === true) { if (is_array($input) === true) {
$output = $this->getValueFromArray($input); $output = $this->getValueFromArray($input);
return (\count($output) === 0) ? $defaultValue : $output; return (count($output) === 0) ? $defaultValue : $output;
} }
return ($input === null || (\is_string($input) && trim($input) === '')) ? $defaultValue : $input; return ($input === null || (is_string($input) && trim($input) === '')) ? $defaultValue : $input;
} }
/** /**
@@ -344,7 +344,7 @@ class InputHandler
public function all(array $filter = []): array public function all(array $filter = []): array
{ {
$output = $this->originalParams + $this->originalPost + $this->originalFile; $output = $this->originalParams + $this->originalPost + $this->originalFile;
$output = (\count($filter) > 0) ? \array_intersect_key($output, \array_flip($filter)) : $output; $output = (count($filter) > 0) ? array_intersect_key($output, array_flip($filter)) : $output;
foreach ($filter as $filterKey) { foreach ($filter as $filterKey) {
if (array_key_exists($filterKey, $output) === false) { if (array_key_exists($filterKey, $output) === false) {
+7 -4
View File
@@ -2,7 +2,10 @@
namespace Pecee\Http\Input; namespace Pecee\Http\Input;
class InputItem implements IInputItem, \IteratorAggregate use ArrayIterator;
use IteratorAggregate;
class InputItem implements IInputItem, IteratorAggregate
{ {
public $index; public $index;
public $name; public $name;
@@ -75,11 +78,11 @@ class InputItem implements IInputItem, \IteratorAggregate
public function __toString(): string public function __toString(): string
{ {
$value = $this->getValue(); $value = $this->getValue();
return (\is_array($value) === true) ? json_encode($value) : $value; return (is_array($value) === true) ? json_encode($value) : $value;
} }
public function getIterator(): \ArrayIterator public function getIterator(): ArrayIterator
{ {
return new \ArrayIterator($this->getValue()); return new ArrayIterator($this->getValue());
} }
} }
@@ -30,17 +30,17 @@ class BaseCsrfVerifier implements IMiddleware
*/ */
protected function skip(Request $request): bool protected function skip(Request $request): bool
{ {
if ($this->except === null || \count($this->except) === 0) { if ($this->except === null || count($this->except) === 0) {
return false; return false;
} }
$max = \count($this->except) - 1; $max = count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) { for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i]; $url = $this->except[$i];
$url = rtrim($url, '/'); $url = rtrim($url, '/');
if ($url[\strlen($url) - 1] === '*') { if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*'); $url = rtrim($url, '*');
$skip = $request->getUrl()->contains($url); $skip = $request->getUrl()->contains($url);
} else { } else {
@@ -2,7 +2,9 @@
namespace Pecee\Http\Middleware\Exceptions; namespace Pecee\Http\Middleware\Exceptions;
class TokenMismatchException extends \Exception use Exception;
class TokenMismatchException extends Exception
{ {
} }
+2 -2
View File
@@ -369,7 +369,7 @@ class Request
*/ */
public function isPostBack(): bool public function isPostBack(): bool
{ {
return \in_array($this->getMethod(), static::$requestTypesPost, true); return in_array($this->getMethod(), static::$requestTypesPost, true);
} }
/** /**
@@ -475,7 +475,7 @@ class Request
*/ */
public function getLoadedRoute(): ?ILoadableRoute public function getLoadedRoute(): ?ILoadableRoute
{ {
return (\count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null; return (count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
} }
/** /**
+3 -2
View File
@@ -2,6 +2,7 @@
namespace Pecee\Http; namespace Pecee\Http;
use JsonSerializable;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
class Response class Response
@@ -85,14 +86,14 @@ class Response
/** /**
* Json encode * Json encode
* @param array|\JsonSerializable $value * @param array|JsonSerializable $value
* @param ?int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR. * @param ?int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param int $dept JSON debt. * @param int $dept JSON debt.
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function json($value, ?int $options = null, int $dept = 512): void public function json($value, ?int $options = null, int $dept = 512): void
{ {
if (($value instanceof \JsonSerializable) === false && \is_array($value) === false) { if (($value instanceof JsonSerializable) === false && is_array($value) === false) {
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.'); throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
} }
@@ -2,6 +2,7 @@
namespace Pecee\Http\Security; namespace Pecee\Http\Security;
use Exception;
use Pecee\Http\Security\Exceptions\SecurityException; use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider class CookieTokenProvider implements ITokenProvider
@@ -34,7 +35,7 @@ class CookieTokenProvider implements ITokenProvider
{ {
try { try {
return bin2hex(random_bytes(32)); return bin2hex(random_bytes(32));
} catch (\Exception $e) { } catch (Exception $e) {
throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious()); throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
} }
} }
@@ -2,7 +2,9 @@
namespace Pecee\Http\Security\Exceptions; namespace Pecee\Http\Security\Exceptions;
class SecurityException extends \Exception use Exception;
class SecurityException extends Exception
{ {
} }
+3 -2
View File
@@ -2,9 +2,10 @@
namespace Pecee\Http; namespace Pecee\Http;
use JsonSerializable;
use Pecee\Http\Exceptions\MalformedUrlException; use Pecee\Http\Exceptions\MalformedUrlException;
class Url implements \JsonSerializable class Url implements JsonSerializable
{ {
private $originalUrl; private $originalUrl;
@@ -409,7 +410,7 @@ class Url implements \JsonSerializable
*/ */
public static function arrayToParams(array $getParams = [], bool $includeEmpty = true): string public static function arrayToParams(array $getParams = [], bool $includeEmpty = true): string
{ {
if (\count($getParams) !== 0) { if (count($getParams) !== 0) {
if ($includeEmpty === false) { if ($includeEmpty === false) {
$getParams = array_filter($getParams, static function ($item) { $getParams = array_filter($getParams, static function ($item) {
@@ -31,7 +31,7 @@ class ClassLoader implements IClassLoader
*/ */
public function loadClosure(Callable $closure, array $parameters) public function loadClosure(Callable $closure, array $parameters)
{ {
return \call_user_func_array($closure, array_values($parameters)); return call_user_func_array($closure, array_values($parameters));
} }
} }
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter\Event; namespace Pecee\SimpleRouter\Event;
use InvalidArgumentException;
use Pecee\Http\Request; use Pecee\Http\Request;
use Pecee\SimpleRouter\Router; use Pecee\SimpleRouter\Router;
@@ -91,11 +92,11 @@ class EventArgument implements IEventArgument
/** /**
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
* @throws \InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function __set(string $name, $value) public function __set(string $name, $value)
{ {
throw new \InvalidArgumentException('Not supported'); throw new InvalidArgumentException('Not supported');
} }
/** /**
@@ -2,7 +2,9 @@
namespace Pecee\SimpleRouter\Exceptions; namespace Pecee\SimpleRouter\Exceptions;
class HttpException extends \Exception use Exception;
class HttpException extends Exception
{ {
} }
@@ -2,6 +2,8 @@
namespace Pecee\SimpleRouter\Handlers; namespace Pecee\SimpleRouter\Handlers;
use Closure;
use Exception;
use Pecee\Http\Request; use Pecee\Http\Request;
/** /**
@@ -17,19 +19,19 @@ class CallbackExceptionHandler implements IExceptionHandler
protected $callback; protected $callback;
public function __construct(\Closure $callback) public function __construct(Closure $callback)
{ {
$this->callback = $callback; $this->callback = $callback;
} }
/** /**
* @param Request $request * @param Request $request
* @param \Exception $error * @param Exception $error
*/ */
public function handleError(Request $request, \Exception $error): void public function handleError(Request $request, Exception $error): void
{ {
/* Fire exceptions */ /* Fire exceptions */
\call_user_func($this->callback, call_user_func($this->callback,
$request, $request,
$error $error
); );
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter\Handlers; namespace Pecee\SimpleRouter\Handlers;
use Closure;
use Pecee\SimpleRouter\Event\EventArgument; use Pecee\SimpleRouter\Event\EventArgument;
use Pecee\SimpleRouter\Router; use Pecee\SimpleRouter\Router;
@@ -10,7 +11,7 @@ class DebugEventHandler implements IEventHandler
/** /**
* Debug callback * Debug callback
* @var \Closure * @var Closure
*/ */
protected $callback; protected $callback;
@@ -52,9 +53,9 @@ class DebugEventHandler implements IEventHandler
/** /**
* Set debug callback * Set debug callback
* *
* @param \Closure $event * @param Closure $event
*/ */
public function setCallback(\Closure $event): void public function setCallback(Closure $event): void
{ {
$this->callback = $event; $this->callback = $event;
} }
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter\Handlers; namespace Pecee\SimpleRouter\Handlers;
use Closure;
use Pecee\SimpleRouter\Event\EventArgument; use Pecee\SimpleRouter\Event\EventArgument;
use Pecee\SimpleRouter\Router; use Pecee\SimpleRouter\Router;
@@ -125,10 +126,10 @@ class EventHandler implements IEventHandler
* Register new event * Register new event
* *
* @param string $name * @param string $name
* @param \Closure $callback * @param Closure $callback
* @return static * @return static
*/ */
public function register(string $name, \Closure $callback): IEventHandler public function register(string $name, Closure $callback): IEventHandler
{ {
if (isset($this->registeredEvents[$name]) === true) { if (isset($this->registeredEvents[$name]) === true) {
$this->registeredEvents[$name][] = $callback; $this->registeredEvents[$name][] = $callback;
@@ -175,7 +176,7 @@ class EventHandler implements IEventHandler
{ {
$events = $this->getEvents(static::EVENT_ALL, $name); $events = $this->getEvents(static::EVENT_ALL, $name);
/* @var $event \Closure */ /* @var $event Closure */
foreach ($events as $event) { foreach ($events as $event) {
$event(new EventArgument($name, $router, $eventArgs)); $event(new EventArgument($name, $router, $eventArgs));
} }
@@ -2,14 +2,15 @@
namespace Pecee\SimpleRouter\Handlers; namespace Pecee\SimpleRouter\Handlers;
use Exception;
use Pecee\Http\Request; use Pecee\Http\Request;
interface IExceptionHandler interface IExceptionHandler
{ {
/** /**
* @param Request $request * @param Request $request
* @param \Exception $error * @param Exception $error
*/ */
public function handleError(Request $request, \Exception $error): void; public function handleError(Request $request, Exception $error): void;
} }
@@ -34,7 +34,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
foreach ($this->getMiddlewares() as $middleware) { foreach ($this->getMiddlewares() as $middleware) {
if (\is_object($middleware) === false) { if (is_object($middleware) === false) {
$middleware = $router->getClassLoader()->loadClass($middleware); $middleware = $router->getClassLoader()->loadClass($middleware);
} }
@@ -42,7 +42,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
throw new HttpException($middleware . ' must be inherit the IMiddleware interface'); throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
} }
$className = \get_class($middleware); $className = get_class($middleware);
$router->debug('Loading middleware "%s"', $className); $router->debug('Loading middleware "%s"', $className);
$middleware->handle($request); $middleware->handle($request);
@@ -116,7 +116,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
$group = $this->getGroup(); $group = $this->getGroup();
if ($group !== null && \count($group->getDomains()) !== 0) { if ($group !== null && count($group->getDomains()) !== 0) {
$url = '//' . $group->getDomains()[0] . $url; $url = '//' . $group->getDomains()[0] . $url;
} }
@@ -132,7 +132,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
foreach (array_keys($params) as $param) { foreach (array_keys($params) as $param) {
if ($parameters === '' || (\is_array($parameters) === true && \count($parameters) === 0)) { if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
$value = ''; $value = '';
} else { } else {
$p = (array)$parameters; $p = (array)$parameters;
+14 -15
View File
@@ -51,7 +51,7 @@ abstract class Route implements IRoute
*/ */
public function renderRoute(Request $request, Router $router): ?string public function renderRoute(Request $request, Router $router): ?string
{ {
$router->debug('Starting rendering route "%s"', \get_class($this)); $router->debug('Starting rendering route "%s"', get_class($this));
$callback = $this->getCallback(); $callback = $this->getCallback();
@@ -73,7 +73,7 @@ abstract class Route implements IRoute
} }
/* Render callback function */ /* Render callback function */
if (\is_callable($callback) === true) { if (is_callable($callback) === true) {
$router->debug('Executing callback'); $router->debug('Executing callback');
/* When the callback is a function */ /* When the callback is a function */
@@ -99,7 +99,7 @@ abstract class Route implements IRoute
$router->debug('Executing callback'); $router->debug('Executing callback');
return \call_user_func_array([$class, $method], $parameters); return call_user_func_array([$class, $method], $parameters);
} }
protected function parseParameters($route, $url, $parameterRegex = null): ?array protected function parseParameters($route, $url, $parameterRegex = null): ?array
@@ -126,7 +126,7 @@ abstract class Route implements IRoute
$regex = ''; $regex = '';
if ($key < \count($parameters[1])) { if ($key < count($parameters[1])) {
$name = $parameters[1][$key]; $name = $parameters[1][$key];
@@ -157,7 +157,7 @@ abstract class Route implements IRoute
/* Only take matched parameters with name */ /* Only take matched parameters with name */
foreach ((array)$parameters[1] as $name) { foreach ((array)$parameters[1] as $name) {
// Skip parent parameters // Ignore parent parameters
if(isset($groupParameters[$name]) === true) { if(isset($groupParameters[$name]) === true) {
continue; continue;
} }
@@ -180,7 +180,7 @@ abstract class Route implements IRoute
*/ */
public function getIdentifier(): string public function getIdentifier(): string
{ {
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) { if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
return $this->callback; return $this->callback;
} }
@@ -239,7 +239,6 @@ abstract class Route implements IRoute
$this->group = $group; $this->group = $group;
/* Add/merge parent settings with child */ /* Add/merge parent settings with child */
return $this->setSettings($group->toArray(), true); return $this->setSettings($group->toArray(), true);
} }
@@ -279,11 +278,11 @@ abstract class Route implements IRoute
public function getMethod(): ?string public function getMethod(): ?string
{ {
if (\is_array($this->callback) === true && \count($this->callback) > 1) { if (is_array($this->callback) === true && count($this->callback) > 1) {
return $this->callback[1]; return $this->callback[1];
} }
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) { if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback); $tmp = explode('@', $this->callback);
return $tmp[1]; return $tmp[1];
@@ -294,11 +293,11 @@ abstract class Route implements IRoute
public function getClass(): ?string public function getClass(): ?string
{ {
if (\is_array($this->callback) === true && \count($this->callback) > 0) { if (is_array($this->callback) === true && count($this->callback) > 0) {
return $this->callback[0]; return $this->callback[0];
} }
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) { if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback); $tmp = explode('@', $this->callback);
return $tmp[0]; return $tmp[0];
@@ -369,15 +368,15 @@ abstract class Route implements IRoute
$values['namespace'] = $this->namespace; $values['namespace'] = $this->namespace;
} }
if (\count($this->requestMethods) !== 0) { if (count($this->requestMethods) !== 0) {
$values['method'] = $this->requestMethods; $values['method'] = $this->requestMethods;
} }
if (\count($this->where) !== 0) { if (count($this->where) !== 0) {
$values['where'] = $this->where; $values['where'] = $this->where;
} }
if (\count($this->middlewares) !== 0) { if (count($this->middlewares) !== 0) {
$values['middleware'] = $this->middlewares; $values['middleware'] = $this->middlewares;
} }
@@ -471,7 +470,7 @@ abstract class Route implements IRoute
/* Sort the parameters after the user-defined param order, if any */ /* Sort the parameters after the user-defined param order, if any */
$parameters = []; $parameters = [];
if (\count($this->originalParameters) !== 0) { if (count($this->originalParameters) !== 0) {
$parameters = $this->originalParameters; $parameters = $this->originalParameters;
} }
@@ -35,7 +35,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$method = substr($name, strrpos($name, '.') + 1); $method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.')); $newName = substr($name, 0, strrpos($name, '.'));
if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) { if (in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
return true; return true;
} }
} }
@@ -67,7 +67,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
foreach (Request::$requestTypes as $requestType) { foreach (Request::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) { if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, \strlen($requestType)); $method = (string)substr($method, strlen($requestType));
break; break;
} }
} }
@@ -77,7 +77,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$group = $this->getGroup(); $group = $this->getGroup();
if ($group !== null && \count($group->getDomains()) !== 0) { if ($group !== null && count($group->getDomains()) !== 0) {
$url .= '//' . $group->getDomains()[0]; $url .= '//' . $group->getDomains()[0];
} }
@@ -102,12 +102,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/'); $strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl); $path = explode('/', $strippedUrl);
if (\count($path) !== 0) { if (count($path) !== 0) {
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0]; $method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method); $this->method = $request->getMethod() . ucfirst($method);
$this->parameters = \array_slice($path, 1); $this->parameters = array_slice($path, 1);
// Set callback // Set callback
$this->setCallback([$this->controller, $this->method]); $this->setCallback([$this->controller, $this->method]);
+3 -3
View File
@@ -20,7 +20,7 @@ class RouteGroup extends Route implements IGroupRoute
*/ */
public function matchDomain(Request $request): bool public function matchDomain(Request $request): bool
{ {
if ($this->domains === null || \count($this->domains) === 0) { if ($this->domains === null || count($this->domains) === 0) {
return true; return true;
} }
@@ -33,7 +33,7 @@ class RouteGroup extends Route implements IGroupRoute
$parameters = $this->parseParameters($domain, $request->getHost(), '.*'); $parameters = $this->parseParameters($domain, $request->getHost(), '.*');
if ($parameters !== null && \count($parameters) !== 0) { if ($parameters !== null && count($parameters) !== 0) {
$this->parameters = $parameters; $this->parameters = $parameters;
return true; return true;
} }
@@ -204,7 +204,7 @@ class RouteGroup extends Route implements IGroupRoute
$values['as'] = $this->name; $values['as'] = $this->name;
} }
if (\count($this->parameters) !== 0) { if (count($this->parameters) !== 0) {
$values['parameters'] = $this->parameters; $values['parameters'] = $this->parameters;
} }
@@ -120,7 +120,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
} }
// Update // Update
if ($id !== null && \in_array($method, [Request::REQUEST_TYPE_PATCH, Request::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']); return $this->call($this->methodNames['update']);
} }
+25 -24
View File
@@ -2,6 +2,7 @@
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Exception;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Exceptions\MalformedUrlException; use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Middleware\BaseCsrfVerifier; use Pecee\Http\Middleware\BaseCsrfVerifier;
@@ -188,7 +189,7 @@ class Router
$route->renderRoute($this->request, $this); $route->renderRoute($this->request, $this);
$this->isProcessingRoute = false; $this->isProcessingRoute = false;
if (\count($this->routeStack) !== 0) { if (count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */ /* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack; $stack = $this->routeStack;
@@ -225,7 +226,7 @@ class Router
/* @var $route IRoute */ /* @var $route IRoute */
foreach ($routes as $route) { foreach ($routes as $route) {
$this->debug('Processing route "%s"', \get_class($route)); $this->debug('Processing route "%s"', get_class($route));
if ($group !== null) { if ($group !== null) {
/* Add the parent group */ /* Add the parent group */
@@ -238,7 +239,7 @@ class Router
if ($route->matchRoute($url, $this->request) === true) { if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */ /* Add exception handlers */
if (\count($route->getExceptionHandlers()) !== 0) { if (count($route->getExceptionHandlers()) !== 0) {
/** @noinspection AdditionOperationOnArraysInspection */ /** @noinspection AdditionOperationOnArraysInspection */
$exceptionHandlers += $route->getExceptionHandlers(); $exceptionHandlers += $route->getExceptionHandlers();
} }
@@ -292,7 +293,7 @@ class Router
/* @var $manager IRouterBootManager */ /* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) { foreach ($this->bootManagers as $manager) {
$className = \get_class($manager); $className = get_class($manager);
$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,
@@ -315,7 +316,7 @@ class Router
* @throws NotFoundHttpException * @throws NotFoundHttpException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException * @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws Exception
*/ */
public function start(): ?string public function start(): ?string
{ {
@@ -351,7 +352,7 @@ class Router
* *
* @return string|null * @return string|null
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws Exception
*/ */
public function routeRequest(): ?string public function routeRequest(): ?string
{ {
@@ -365,7 +366,7 @@ class Router
/* @var $route ILoadableRoute */ /* @var $route ILoadableRoute */
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));
/* If the route matches */ /* If the route matches */
if ($route->matchRoute($url, $this->request) === true) { if ($route->matchRoute($url, $this->request) === true) {
@@ -375,7 +376,7 @@ class Router
]); ]);
/* Check if request method matches */ /* Check if request method matches */
if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) { if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$this->debug('Method "%s" not allowed', $this->request->getMethod()); $this->debug('Method "%s" not allowed', $this->request->getMethod());
// Only set method not allowed is not already set // Only set method not allowed is not already set
@@ -425,7 +426,7 @@ class Router
} }
} }
} catch (\Exception $e) { } catch (Exception $e) {
$this->handleException($e); $this->handleException($e);
} }
@@ -434,7 +435,7 @@ class Router
$this->handleException(new NotFoundHttpException($message, 403)); $this->handleException(new NotFoundHttpException($message, 403));
} }
if (\count($this->request->getLoadedRoutes()) === 0) { if (count($this->request->getLoadedRoutes()) === 0) {
$rewriteUrl = $this->request->getRewriteUrl(); $rewriteUrl = $this->request->getRewriteUrl();
@@ -459,7 +460,7 @@ class Router
* @param string $url * @param string $url
* @return string|null * @return string|null
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws Exception
*/ */
protected function handleRouteRewrite(string $key, string $url): ?string protected function handleRouteRewrite(string $key, string $url): ?string
{ {
@@ -493,14 +494,14 @@ class Router
} }
/** /**
* @param \Exception $e * @param Exception $e
* @return string|null * @return string|null
* @throws \Exception * @throws Exception
* @throws HttpException * @throws HttpException
*/ */
protected function handleException(\Exception $e): ?string protected function handleException(Exception $e): ?string
{ {
$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,
@@ -510,7 +511,7 @@ class Router
/* @var $handler IExceptionHandler */ /* @var $handler IExceptionHandler */
foreach ($this->exceptionHandlers as $key => $handler) { foreach ($this->exceptionHandlers as $key => $handler) {
if (\is_object($handler) === false) { if (is_object($handler) === false) {
$handler = new $handler(); $handler = new $handler();
} }
@@ -520,7 +521,7 @@ class Router
'exceptionHandlers' => $this->exceptionHandlers, 'exceptionHandlers' => $this->exceptionHandlers,
]); ]);
$this->debug('Processing exception-handler "%s"', \get_class($handler)); $this->debug('Processing exception-handler "%s"', get_class($handler));
if (($handler instanceof IExceptionHandler) === false) { if (($handler instanceof IExceptionHandler) === false) {
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500); throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
@@ -549,7 +550,7 @@ class Router
return $this->routeRequest(); return $this->routeRequest();
} }
} catch (\Exception $e) { } catch (Exception $e) {
} }
@@ -592,7 +593,7 @@ class Router
} }
/* Using @ is most definitely a controller@method or alias@method */ /* Using @ is most definitely a controller@method or alias@method */
if (\is_string($name) === true && strpos($name, '@') !== false) { if (is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = array_map('strtolower', explode('@', $name)); [$controller, $method] = array_map('strtolower', explode('@', $name));
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) { if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
@@ -604,7 +605,7 @@ class Router
/* Check if callback matches (if it's not a function) */ /* Check if callback matches (if it's not a function) */
$callback = $route->getCallback(); $callback = $route->getCallback();
if (\is_string($name) === true && \is_string($callback) === true && \is_callable($callback) === false && strpos($name, '@') !== false && strpos($callback, '@') !== false) { if (is_string($name) === true && is_string($callback) === true && is_callable($callback) === false && strpos($name, '@') !== false && strpos($callback, '@') !== false) {
/* Check if the entire callback is matching */ /* Check if the entire callback is matching */
if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) { if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) {
@@ -647,7 +648,7 @@ class Router
*/ */
public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url
{ {
$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,
@@ -655,7 +656,7 @@ class Router
'getParams' => $getParams, 'getParams' => $getParams,
]); ]);
if ($getParams !== null && \is_array($getParams) === false) { if ($getParams !== null && is_array($getParams) === false) {
throw new InvalidArgumentException('Invalid type for getParams. Must be array or null'); throw new InvalidArgumentException('Invalid type for getParams. Must be array or null');
} }
@@ -696,7 +697,7 @@ class Router
} }
/* Using @ is most definitely a controller@method or alias@method */ /* Using @ is most definitely a controller@method or alias@method */
if (\is_string($name) === true && strpos($name, '@') !== false) { if (is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = explode('@', $name); [$controller, $method] = explode('@', $name);
/* Loop through all the routes to see if we can find a match */ /* Loop through all the routes to see if we can find a match */
@@ -876,7 +877,7 @@ class Router
*/ */
protected function fireEvents(string $name, array $arguments = []): void protected function fireEvents(string $name, array $arguments = []): void
{ {
if (\count($this->eventHandlers) === 0) { if (count($this->eventHandlers) === 0) {
return; return;
} }
+25 -23
View File
@@ -10,6 +10,8 @@
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Closure;
use Exception;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Middleware\BaseCsrfVerifier; use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -54,7 +56,7 @@ class SimpleRouter
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException * @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws Exception
*/ */
public static function start(): void public static function start(): void
{ {
@@ -79,18 +81,18 @@ class SimpleRouter
ob_start(); ob_start();
static::router()->setDebugEnabled(true)->start(); static::router()->setDebugEnabled(true)->start();
$routerOutput = ob_get_clean(); $routerOutput = ob_get_clean();
} catch (\Exception $e) { } catch (Exception $e) {
} }
// Try to parse library version // Try to parse library version
$composerFile = \dirname(__DIR__, 3) . '/composer.lock'; $composerFile = dirname(__DIR__, 3) . '/composer.lock';
$version = false; $version = false;
if (is_file($composerFile) === true) { if (is_file($composerFile) === true) {
$composerInfo = json_decode(file_get_contents($composerFile), true); $composerInfo = json_decode(file_get_contents($composerFile), true);
if (isset($composerInfo['packages']) === true && \is_array($composerInfo['packages']) === true) { if (isset($composerInfo['packages']) === true && is_array($composerInfo['packages']) === true) {
foreach ($composerInfo['packages'] as $package) { foreach ($composerInfo['packages'] as $package) {
if (isset($package['name']) === true && strtolower($package['name']) === 'pecee/simple-router') { if (isset($package['name']) === true && strtolower($package['name']) === 'pecee/simple-router') {
$version = $package['version']; $version = $package['version'];
@@ -180,7 +182,7 @@ class SimpleRouter
* Route the given url to your callback on GET request method. * Route the given url to your callback on GET request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* *
* @return RouteUrl * @return RouteUrl
@@ -194,7 +196,7 @@ class SimpleRouter
* Route the given url to your callback on POST request method. * Route the given url to your callback on POST request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
*/ */
@@ -207,7 +209,7 @@ class SimpleRouter
* Route the given url to your callback on PUT request method. * Route the given url to your callback on PUT request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
*/ */
@@ -220,7 +222,7 @@ class SimpleRouter
* Route the given url to your callback on PATCH request method. * Route the given url to your callback on PATCH request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
*/ */
@@ -233,7 +235,7 @@ class SimpleRouter
* Route the given url to your callback on OPTIONS request method. * Route the given url to your callback on OPTIONS request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
*/ */
@@ -246,7 +248,7 @@ class SimpleRouter
* Route the given url to your callback on DELETE request method. * Route the given url to your callback on DELETE request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
*/ */
@@ -259,13 +261,13 @@ class SimpleRouter
* Groups allows for encapsulating routes with special settings. * Groups allows for encapsulating routes with special settings.
* *
* @param array $settings * @param array $settings
* @param \Closure $callback * @param Closure $callback
* @return RouteGroup * @return RouteGroup
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function group(array $settings, \Closure $callback): IGroupRoute public static function group(array $settings, Closure $callback): IGroupRoute
{ {
if (\is_callable($callback) === false) { if (is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
} }
@@ -283,14 +285,14 @@ class SimpleRouter
* parameters and which are only rendered when the url matches. * parameters and which are only rendered when the url matches.
* *
* @param string $url * @param string $url
* @param \Closure $callback * @param Closure $callback
* @param array $settings * @param array $settings
* @return RoutePartialGroup * @return RoutePartialGroup
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function partialGroup(string $url, \Closure $callback, array $settings = []): IPartialGroupRoute public static function partialGroup(string $url, Closure $callback, array $settings = []): IPartialGroupRoute
{ {
if (\is_callable($callback) === false) { if (is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
} }
@@ -309,7 +311,7 @@ class SimpleRouter
* Alias for the form method * Alias for the form method
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
* @see SimpleRouter::form * @see SimpleRouter::form
@@ -324,7 +326,7 @@ class SimpleRouter
* Route the given url to your callback on POST and GET request method. * Route the given url to your callback on POST and GET request method.
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl * @return RouteUrl
* @see SimpleRouter::form * @see SimpleRouter::form
@@ -342,7 +344,7 @@ class SimpleRouter
* *
* @param array $requestMethods * @param array $requestMethods
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl|IRoute * @return RouteUrl|IRoute
*/ */
@@ -362,7 +364,7 @@ class SimpleRouter
* This type will route the given url to your callback and allow any type of request method * This type will route the given url to your callback and allow any type of request method
* *
* @param string $url * @param string $url
* @param string|array|\Closure $callback * @param string|array|Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouteUrl|IRoute * @return RouteUrl|IRoute
*/ */
@@ -418,10 +420,10 @@ class SimpleRouter
/** /**
* Add exception callback handler. * Add exception callback handler.
* *
* @param \Closure $callback * @param Closure $callback
* @return CallbackExceptionHandler $callbackHandler * @return CallbackExceptionHandler $callbackHandler
*/ */
public static function error(\Closure $callback): CallbackExceptionHandler public static function error(Closure $callback): CallbackExceptionHandler
{ {
$routes = static::router()->getRoutes(); $routes = static::router()->getRoutes();
@@ -458,7 +460,7 @@ class SimpleRouter
{ {
try { try {
return static::router()->getUrl($name, $parameters, $getParams); return static::router()->getUrl($name, $parameters, $getParams);
} catch (\Exception $e) { } catch (Exception $e) {
return new Url('/'); return new Url('/');
} }
} }