Added support for PHP7

This commit is contained in:
Simon Sessingø
2018-03-20 03:38:55 +01:00
parent d279d5598d
commit f23d569757
58 changed files with 678 additions and 532 deletions
+22
View File
@@ -0,0 +1,22 @@
engines:
phpmd:
enabled: true
checks:
Design/TooManyPublicMethods:
enabled: true
Naming/ShortVariable:
enabled: true
CleanCode/StaticAccess:
enabled: true
Controversial/CamelCaseMethodName:
enabled: true
fixme:
enabled: true
duplication:
enabled: true
config:
languages:
- php:
ratings:
paths:
- src/**
+13
View File
@@ -0,0 +1,13 @@
build:
tests:
override:
-
command: './vendor/bin/phpunit --coverage-clover=coverage.clover'
coverage:
file: 'coverage.clover'
format: 'clover'
checks:
php:
code_rating: true
duplication: true
+13
View File
@@ -0,0 +1,13 @@
sudo: false
language: php
php:
- 7.1
before_script:
- curl -sS http://getcomposer.org/installer | php
- php composer.phar install --prefer-source --no-interaction
script:
- ./vendor/bin/phpunit
+10 -4
View File
@@ -308,6 +308,8 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param string|array|null $parameters * @param string|array|null $parameters
* @param array|null $getParams * @param array|null $getParams
* @return string * @return string
* @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function url($name = null, $parameters = null, $getParams = null) function url($name = null, $parameters = null, $getParams = null)
{ {
@@ -316,6 +318,7 @@ function url($name = null, $parameters = null, $getParams = null)
/** /**
* @return \Pecee\Http\Response * @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function response() function response()
{ {
@@ -324,6 +327,7 @@ function response()
/** /**
* @return \Pecee\Http\Request * @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function request() function request()
{ {
@@ -335,15 +339,16 @@ function request()
* @param string|null $index Parameter index name * @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value * @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method * @param string|array|null $methods Default method
* @return \Pecee\Http\Input\Input|string * @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function input($index = null, $defaultValue = null, $methods = null) function input($index = null, $defaultValue = null, $methods = null)
{ {
if ($index !== null) { if ($index !== null) {
return request()->getInput()->get($index, $defaultValue, $methods); return request()->getInputHandler()->get($index, $defaultValue, $methods);
} }
return request()->getInput(); return request()->getInputHandler();
} }
function redirect($url, $code = null) function redirect($url, $code = null)
@@ -358,12 +363,13 @@ function redirect($url, $code = null)
/** /**
* Get current csrf-token * Get current csrf-token
* @return string|null * @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function csrf_token() function csrf_token()
{ {
$baseVerifier = Router::router()->getCsrfVerifier(); $baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) { if ($baseVerifier !== null) {
return $baseVerifier->getToken(); return $baseVerifier->getTokenProvider()->getToken();
} }
return null; return null;
+3 -2
View File
@@ -27,10 +27,11 @@
} }
], ],
"require": { "require": {
"php": ">=5.4.0" "php": ">=7.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "4.7.7" "phpunit/phpunit": "^6.0",
"mockery/mockery": "^1"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
+8 -3
View File
@@ -19,6 +19,7 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param array|null $getParams * @param array|null $getParams
* @return string * @return string
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function url($name = null, $parameters = null, $getParams = null) function url($name = null, $parameters = null, $getParams = null)
{ {
@@ -27,6 +28,7 @@ function url($name = null, $parameters = null, $getParams = null)
/** /**
* @return \Pecee\Http\Response * @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function response() function response()
{ {
@@ -35,6 +37,7 @@ function response()
/** /**
* @return \Pecee\Http\Request * @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function request() function request()
{ {
@@ -46,15 +49,16 @@ function request()
* @param string|null $index Parameter index name * @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value * @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method * @param string|array|null $methods Default method
* @return \Pecee\Http\Input\Input|string * @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function input($index = null, $defaultValue = null, $methods = null) function input($index = null, $defaultValue = null, $methods = null)
{ {
if ($index !== null) { if ($index !== null) {
return request()->getInput()->get($index, $defaultValue, $methods); return request()->getInputHandler()->get($index, $defaultValue, $methods);
} }
return request()->getInput(); return request()->getInputHandler();
} }
function redirect($url, $code = null) function redirect($url, $code = null)
@@ -69,6 +73,7 @@ function redirect($url, $code = null)
/** /**
* Get current csrf-token * Get current csrf-token
* @return string|null * @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function csrf_token() function csrf_token()
{ {
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
bootstrap="tests/bootstrap.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="SimpleRouter Test Suite">
<directory>tests/Pecee/SimpleRouter/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
+15 -14
View File
@@ -1,47 +1,48 @@
<?php <?php
namespace Pecee\Controllers; namespace Pecee\Controllers;
interface IResourceController interface IResourceController
{ {
/** /**
* @return void * @return string|null
*/ */
public function index(); public function index(): ?string;
/** /**
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function show($id); public function show($id): ?string;
/** /**
* @return void * @return string|null
*/ */
public function store(); public function store(): ?string;
/** /**
* @return void * @return string|null
*/ */
public function create(); public function create(): ?string;
/** /**
* View * View
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function edit($id); public function edit($id): ?string;
/** /**
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function update($id); public function update($id): ?string;
/** /**
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function destroy($id); public function destroy($id): ?string;
} }
@@ -25,12 +25,11 @@ class CallbackExceptionHandler implements IExceptionHandler
/** /**
* @param Request $request * @param Request $request
* @param \Exception $error * @param \Exception $error
* @return Request|null
*/ */
public function handleError(Request $request, \Exception $error) public function handleError(Request $request, \Exception $error): void
{ {
/* Fire exceptions */ /* Fire exceptions */
return call_user_func($this->callback, \call_user_func($this->callback,
$request, $request,
$error $error
); );
+2 -2
View File
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\Handlers; namespace Pecee\Handlers;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -8,8 +9,7 @@ interface IExceptionHandler
/** /**
* @param Request $request * @param Request $request
* @param \Exception $error * @param \Exception $error
* @return Request|null
*/ */
public function handleError(Request $request, \Exception $error); public function handleError(Request $request, \Exception $error): void;
} }
+6 -6
View File
@@ -5,17 +5,17 @@ namespace Pecee\Http\Input;
interface IInputItem interface IInputItem
{ {
public function getIndex(); public function getIndex(): string;
public function setIndex($index); public function setIndex($index): self;
public function getName(); public function getName(): string;
public function setName($name); public function setName($name): self;
public function getValue(); public function getValue(): string;
public function setValue($value); public function setValue($value): self;
public function __toString(); public function __toString();
+30 -30
View File
@@ -31,7 +31,7 @@ class InputFile implements IInputItem
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return static * @return static
*/ */
public static function createFromArray(array $values) public static function createFromArray(array $values): self
{ {
if (isset($values['index']) === false) { if (isset($values['index']) === false) {
throw new InvalidArgumentException('Index key is required'); throw new InvalidArgumentException('Index key is required');
@@ -59,7 +59,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getIndex() public function getIndex(): string
{ {
return $this->index; return $this->index;
} }
@@ -67,9 +67,9 @@ class InputFile implements IInputItem
/** /**
* Set input index * Set input index
* @param string $index * @param string $index
* @return static $this * @return static
*/ */
public function setIndex($index) public function setIndex($index): IInputItem
{ {
$this->index = $index; $this->index = $index;
@@ -79,7 +79,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getSize() public function getSize(): string
{ {
return $this->size; return $this->size;
} }
@@ -87,9 +87,9 @@ class InputFile implements IInputItem
/** /**
* Set file size * Set file size
* @param int $size * @param int $size
* @return static $this * @return static
*/ */
public function setSize($size) public function setSize($size): IInputItem
{ {
$this->size = $size; $this->size = $size;
@@ -100,7 +100,7 @@ class InputFile implements IInputItem
* Get mime-type of file * Get mime-type of file
* @return string * @return string
*/ */
public function getMime() public function getMime(): string
{ {
return $this->getType(); return $this->getType();
} }
@@ -108,7 +108,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getType() public function getType(): string
{ {
return $this->type; return $this->type;
} }
@@ -116,9 +116,9 @@ class InputFile implements IInputItem
/** /**
* Set type * Set type
* @param string $type * @param string $type
* @return static $this * @return static
*/ */
public function setType($type) public function setType($type): IInputItem
{ {
$this->type = $type; $this->type = $type;
@@ -130,7 +130,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getExtension() public function getExtension(): string
{ {
return pathinfo($this->getFilename(), PATHINFO_EXTENSION); return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
} }
@@ -140,7 +140,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getName() public function getName(): string
{ {
return $this->name; return $this->name;
} }
@@ -150,9 +150,9 @@ class InputFile implements IInputItem
* Useful for adding validation etc. * Useful for adding validation etc.
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name) public function setName($name): IInputItem
{ {
$this->name = $name; $this->name = $name;
@@ -163,9 +163,9 @@ class InputFile implements IInputItem
* Set filename * Set filename
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setFilename($name) public function setFilename($name): IInputItem
{ {
$this->filename = $name; $this->filename = $name;
@@ -177,7 +177,7 @@ class InputFile implements IInputItem
* *
* @return string mixed * @return string mixed
*/ */
public function getFilename() public function getFilename(): string
{ {
return $this->filename; return $this->filename;
} }
@@ -188,7 +188,7 @@ class InputFile implements IInputItem
* @param string $destination * @param string $destination
* @return bool * @return bool
*/ */
public function move($destination) public function move($destination): bool
{ {
return move_uploaded_file($this->tmpName, $destination); return move_uploaded_file($this->tmpName, $destination);
} }
@@ -198,7 +198,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getContents() public function getContents(): string
{ {
return file_get_contents($this->tmpName); return file_get_contents($this->tmpName);
} }
@@ -208,7 +208,7 @@ class InputFile implements IInputItem
* *
* @return bool * @return bool
*/ */
public function hasError() public function hasError(): bool
{ {
return ($this->getError() !== 0); return ($this->getError() !== 0);
} }
@@ -218,7 +218,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getError() public function getError(): string
{ {
return $this->errors; return $this->errors;
} }
@@ -227,9 +227,9 @@ class InputFile implements IInputItem
* Set error * Set error
* *
* @param int $error * @param int $error
* @return static $this * @return static
*/ */
public function setError($error) public function setError($error): IInputItem
{ {
$this->errors = (int)$error; $this->errors = (int)$error;
@@ -239,7 +239,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getTmpName() public function getTmpName(): string
{ {
return $this->tmpName; return $this->tmpName;
} }
@@ -247,9 +247,9 @@ class InputFile implements IInputItem
/** /**
* Set file temp. name * Set file temp. name
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setTmpName($name) public function setTmpName($name): IInputItem
{ {
$this->tmpName = $name; $this->tmpName = $name;
@@ -261,7 +261,7 @@ class InputFile implements IInputItem
return $this->getTmpName(); return $this->getTmpName();
} }
public function getValue() public function getValue(): string
{ {
return $this->getFilename(); return $this->getFilename();
} }
@@ -270,14 +270,14 @@ class InputFile implements IInputItem
* @param string $value * @param string $value
* @return static * @return static
*/ */
public function setValue($value) public function setValue($value): IInputItem
{ {
$this->filename = $value; $this->filename = $value;
return $this; return $this;
} }
public function toArray() public function toArray(): array
{ {
return [ return [
'tmp_name' => $this->tmpName, 'tmp_name' => $this->tmpName,
@@ -5,7 +5,7 @@ namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Request; use Pecee\Http\Request;
class Input class InputHandler
{ {
/** /**
* @var array * @var array
@@ -42,26 +42,26 @@ class Input
* Parse input values * Parse input values
* *
*/ */
public function parseInputs() public function parseInputs() : void
{ {
/* Parse get requests */ /* Parse get requests */
if (count($_GET) !== 0) { if (\count($_GET) !== 0) {
$this->get = $this->handleGetPost($_GET); $this->get = $this->handleGetPost($_GET);
} }
/* Parse post requests */ /* Parse post requests */
$postVars = $_POST; $postVars = $_POST;
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) { if (\in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
parse_str(file_get_contents('php://input'), $postVars); parse_str(file_get_contents('php://input'), $postVars);
} }
if (count($postVars) !== 0) { if (\count($postVars) !== 0) {
$this->post = $this->handleGetPost($postVars); $this->post = $this->handleGetPost($postVars);
} }
/* Parse get requests */ /* Parse get requests */
if (count($_FILES) !== 0) { if (\count($_FILES) !== 0) {
$this->file = $this->parseFiles(); $this->file = $this->parseFiles();
} }
} }
@@ -69,14 +69,14 @@ class Input
/** /**
* @return array * @return array
*/ */
public function parseFiles() public function parseFiles() : array
{ {
$list = []; $list = [];
foreach ((array)$_FILES as $key => $value) { foreach ((array)$_FILES as $key => $value) {
// Handle array input // Handle array input
if (is_array($value['name']) === false) { if (\is_array($value['name']) === false) {
$values['index'] = $key; $values['index'] = $key;
try { try {
$list[$key] = InputFile::createFromArray($values + $value); $list[$key] = InputFile::createFromArray($values + $value);
@@ -101,7 +101,7 @@ class Input
return $list; return $list;
} }
protected function rearrangeFiles(array $values, &$index, $original) protected function rearrangeFiles(array $values, &$index, $original) : array
{ {
$originalIndex = $index[0]; $originalIndex = $index[0];
@@ -111,7 +111,7 @@ class Input
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 {
@@ -152,14 +152,14 @@ class Input
return $output; return $output;
} }
protected function handleGetPost(array $array) protected function handleGetPost(array $array) : array
{ {
$list = []; $list = [];
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
// Handle array input // Handle array input
if (is_array($value) === false) { if (\is_array($value) === false) {
$list[$key] = new InputItem($key, $value); $list[$key] = new InputItem($key, $value);
continue; continue;
} }
@@ -181,7 +181,7 @@ class Input
*/ */
public function findPost($index, $defaultValue = null) public function findPost($index, $defaultValue = null)
{ {
return isset($this->post[$index]) ? $this->post[$index] : $defaultValue; return $this->post[$index] ?? $defaultValue;
} }
/** /**
@@ -193,7 +193,7 @@ class Input
*/ */
public function findFile($index, $defaultValue = null) public function findFile($index, $defaultValue = null)
{ {
return isset($this->file[$index]) ? $this->file[$index] : $defaultValue; return $this->file[$index] ?? $defaultValue;
} }
/** /**
@@ -205,7 +205,7 @@ class Input
*/ */
public function findGet($index, $defaultValue = null) public function findGet($index, $defaultValue = null)
{ {
return isset($this->get[$index]) ? $this->get[$index] : $defaultValue; return $this->get[$index] ?? $defaultValue;
} }
/** /**
@@ -218,25 +218,25 @@ class Input
*/ */
public function getObject($index, $defaultValue = null, $methods = null) public function getObject($index, $defaultValue = null, $methods = null)
{ {
if ($methods !== null && is_string($methods) === true) { if ($methods !== null && \is_string($methods) === true) {
$methods = [$methods]; $methods = [$methods];
} }
$element = null; $element = null;
if ($methods === null || in_array('get', $methods, false) === true) { if ($methods === null || \in_array('get', $methods, true) === true) {
$element = $this->findGet($index); $element = $this->findGet($index);
} }
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods, false) === true)) { if (($element === null && $methods === null) || ($methods !== null && \in_array('post', $methods, true) === true)) {
$element = $this->findPost($index); $element = $this->findPost($index);
} }
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods, false) === true)) { if (($element === null && $methods === null) || ($methods !== null && \in_array('file', $methods, true) === true)) {
$element = $this->findFile($index); $element = $this->findFile($index);
} }
return ($element !== null) ? $element : $defaultValue; return $element ?? $defaultValue;
} }
/** /**
@@ -264,7 +264,7 @@ class Input
* @param string $index * @param string $index
* @return bool * @return bool
*/ */
public function exists($index) public function exists($index) : bool
{ {
return ($this->getObject($index) !== null); return ($this->getObject($index) !== null);
} }
@@ -274,7 +274,7 @@ class Input
* @param array|null $filter Only take items in filter * @param array|null $filter Only take items in filter
* @return array * @return array
*/ */
public function all(array $filter = null) public function all(array $filter = null) : array
{ {
$output = $_GET + $_POST; $output = $_GET + $_POST;
+6 -6
View File
@@ -20,12 +20,12 @@ class InputItem implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getIndex() public function getIndex(): string
{ {
return $this->index; return $this->index;
} }
public function setIndex($index) public function setIndex($index): IInputItem
{ {
$this->index = $index; $this->index = $index;
@@ -35,7 +35,7 @@ class InputItem implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getName() public function getName(): string
{ {
return $this->name; return $this->name;
} }
@@ -45,7 +45,7 @@ class InputItem implements IInputItem
* @param string $name * @param string $name
* @return static $this * @return static $this
*/ */
public function setName($name) public function setName($name): IInputItem
{ {
$this->name = $name; $this->name = $name;
@@ -55,7 +55,7 @@ class InputItem implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getValue() public function getValue(): string
{ {
return $this->value; return $this->value;
} }
@@ -65,7 +65,7 @@ class InputItem implements IInputItem
* @param string $value * @param string $value
* @return static $this * @return static $this
*/ */
public function setValue($value) public function setValue($value): IInputItem
{ {
$this->value = $value; $this->value = $value;
+12 -12
View File
@@ -9,8 +9,8 @@ use Pecee\Http\Security\ITokenProvider;
class BaseCsrfVerifier implements IMiddleware class BaseCsrfVerifier implements IMiddleware
{ {
const POST_KEY = 'csrf-token'; public const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN'; public const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except; protected $except;
protected $tokenProvider; protected $tokenProvider;
@@ -29,21 +29,21 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
protected function skip(Request $request) 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 = (stripos($request->getUrl()->getOriginalUrl(), $url) === 0); $skip = $request->getUrl()->contains($url);
} else { } else {
$skip = ($url === $request->getUrl()->getOriginalUrl()); $skip = ($url === $request->getUrl()->getOriginalUrl());
} }
@@ -62,12 +62,12 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request * @param Request $request
* @throws TokenMismatchException * @throws TokenMismatchException
*/ */
public function handle(Request $request) public function handle(Request $request): void
{ {
if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) { if ($this->skip($request) === false && \in_array($request->getMethod(), ['post', 'put', 'delete'], true) === true) {
$token = $request->getInput()->get(static::POST_KEY, null, 'post'); $token = $request->getInputHandler()->get(static::POST_KEY, null, 'post');
// If the token is not posted, check headers for valid x-csrf-token // If the token is not posted, check headers for valid x-csrf-token
if ($token === null) { if ($token === null) {
@@ -85,7 +85,7 @@ class BaseCsrfVerifier implements IMiddleware
} }
public function getTokenProvider() public function getTokenProvider(): ITokenProvider
{ {
return $this->tokenProvider; return $this->tokenProvider;
} }
@@ -94,7 +94,7 @@ class BaseCsrfVerifier implements IMiddleware
* Set token provider * Set token provider
* @param ITokenProvider $provider * @param ITokenProvider $provider
*/ */
public function setTokenProvider(ITokenProvider $provider) public function setTokenProvider(ITokenProvider $provider): void
{ {
$this->tokenProvider = $provider; $this->tokenProvider = $provider;
} }
+2 -2
View File
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\Http\Middleware; namespace Pecee\Http\Middleware;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -7,8 +8,7 @@ interface IMiddleware
{ {
/** /**
* @param Request $request * @param Request $request
* @return Request|null
*/ */
public function handle(Request $request); public function handle(Request $request): void;
} }
+76 -53
View File
@@ -2,7 +2,7 @@
namespace Pecee\Http; namespace Pecee\Http;
use Pecee\Http\Input\Input; use Pecee\Http\Input\InputHandler;
use Pecee\SimpleRouter\Route\ILoadableRoute; use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl; use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter; use Pecee\SimpleRouter\SimpleRouter;
@@ -14,7 +14,7 @@ class Request
protected $host; protected $host;
protected $url; protected $url;
protected $method; protected $method;
protected $input; protected $inputHandler;
protected $hasRewrite = false; protected $hasRewrite = false;
@@ -25,9 +25,9 @@ class Request
protected $rewriteUrl; protected $rewriteUrl;
/** /**
* @var ILoadableRoute|null * @var array
*/ */
protected $loadedRoute; protected $loadedRoutes = [];
/** /**
* Request constructor. * Request constructor.
@@ -41,11 +41,11 @@ class Request
// Check if special IIS header exist, otherwise use default. // Check if special IIS header exist, otherwise use default.
$this->setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri'))); $this->setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri')));
$this->input = new Input($this); $this->inputHandler = new InputHandler($this);
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'))); $this->method = strtolower($this->inputHandler->get('_method', $this->getHeader('request-method')));
} }
protected function parseHeaders() protected function parseHeaders(): void
{ {
$this->headers = []; $this->headers = [];
@@ -56,7 +56,7 @@ class Request
} }
public function isSecure() public function isSecure(): bool
{ {
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443; return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443;
} }
@@ -64,23 +64,23 @@ class Request
/** /**
* @return Url * @return Url
*/ */
public function getUrl() public function getUrl(): Url
{ {
return $this->url; return $this->url;
} }
/** /**
* @return string * @return string|null
*/ */
public function getHost() public function getHost(): ?string
{ {
return $this->host; return $this->host;
} }
/** /**
* @return string * @return string|null
*/ */
public function getMethod() public function getMethod(): ?string
{ {
return $this->method; return $this->method;
} }
@@ -89,7 +89,7 @@ class Request
* Get http basic auth user * Get http basic auth user
* @return string|null * @return string|null
*/ */
public function getUser() public function getUser(): ?string
{ {
return $this->getHeader('php-auth-user'); return $this->getHeader('php-auth-user');
} }
@@ -98,7 +98,7 @@ class Request
* Get http basic auth password * Get http basic auth password
* @return string|null * @return string|null
*/ */
public function getPassword() public function getPassword(): ?string
{ {
return $this->getHeader('php-auth-pw'); return $this->getHeader('php-auth-pw');
} }
@@ -107,16 +107,16 @@ class Request
* Get all headers * Get all headers
* @return array * @return array
*/ */
public function getHeaders() public function getHeaders(): array
{ {
return $this->headers; return $this->headers;
} }
/** /**
* Get id address * Get id address
* @return string * @return string|null
*/ */
public function getIp() public function getIp(): ?string
{ {
if ($this->getHeader('http-cf-connecting-ip') !== null) { if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip'); return $this->getHeader('http-cf-connecting-ip');
@@ -133,27 +133,27 @@ class Request
* Get remote address/ip * Get remote address/ip
* *
* @alias static::getIp * @alias static::getIp
* @return string * @return string|null
*/ */
public function getRemoteAddr() public function getRemoteAddr(): ?string
{ {
return $this->getIp(); return $this->getIp();
} }
/** /**
* Get referer * Get referer
* @return string * @return string|null
*/ */
public function getReferer() public function getReferer(): ?string
{ {
return $this->getHeader('http-referer'); return $this->getHeader('http-referer');
} }
/** /**
* Get user agent * Get user agent
* @return string * @return string|null
*/ */
public function getUserAgent() public function getUserAgent(): ?string
{ {
return $this->getHeader('http-user-agent'); return $this->getHeader('http-user-agent');
} }
@@ -166,18 +166,18 @@ class Request
* *
* @return string|null * @return string|null
*/ */
public function getHeader($name, $defaultValue = null) public function getHeader($name, $defaultValue = null): ?string
{ {
return isset($this->headers[strtolower($name)]) ? $this->headers[strtolower($name)] : $defaultValue; return $this->headers[strtolower($name)] ?? $defaultValue;
} }
/** /**
* Get input class * Get input class
* @return Input * @return InputHandler
*/ */
public function getInput() public function getInputHandler(): InputHandler
{ {
return $this->input; return $this->inputHandler;
} }
/** /**
@@ -187,9 +187,9 @@ class Request
* *
* @return bool * @return bool
*/ */
public function isFormatAccepted($format) public function isFormatAccepted($format): bool
{ {
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1); return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) !== false);
} }
/** /**
@@ -197,7 +197,7 @@ class Request
* *
* @return bool * @return bool
*/ */
public function isAjax() public function isAjax(): bool
{ {
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest'); return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
} }
@@ -206,7 +206,7 @@ class Request
* Get accept formats * Get accept formats
* @return array * @return array
*/ */
public function getAcceptFormats() public function getAcceptFormats(): array
{ {
return explode(',', $this->getHeader('http-accept')); return explode(',', $this->getHeader('http-accept'));
} }
@@ -215,7 +215,7 @@ class Request
* @param string|Url $url * @param string|Url $url
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public function setUrl($url) public function setUrl($url): void
{ {
$this->url = ($url instanceof Url) ? $url : new Url($url); $this->url = ($url instanceof Url) ? $url : new Url($url);
} }
@@ -223,7 +223,7 @@ class Request
/** /**
* @param string $host * @param string $host
*/ */
public function setHost($host) public function setHost($host): void
{ {
$this->host = $host; $this->host = $host;
} }
@@ -231,7 +231,7 @@ class Request
/** /**
* @param string $method * @param string $method
*/ */
public function setMethod($method) public function setMethod($method): void
{ {
$this->method = $method; $this->method = $method;
} }
@@ -242,7 +242,7 @@ class Request
* @param ILoadableRoute $route * @param ILoadableRoute $route
* @return static * @return static
*/ */
public function setRewriteRoute(ILoadableRoute $route) public function setRewriteRoute(ILoadableRoute $route): self
{ {
$this->hasRewrite = true; $this->hasRewrite = true;
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route); $this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
@@ -255,7 +255,7 @@ class Request
* *
* @return ILoadableRoute|null * @return ILoadableRoute|null
*/ */
public function getRewriteRoute() public function getRewriteRoute(): ?ILoadableRoute
{ {
return $this->rewriteRoute; return $this->rewriteRoute;
} }
@@ -263,9 +263,9 @@ class Request
/** /**
* Get rewrite url * Get rewrite url
* *
* @return string * @return string|null
*/ */
public function getRewriteUrl() public function getRewriteUrl(): ?string
{ {
return $this->rewriteUrl; return $this->rewriteUrl;
} }
@@ -276,7 +276,7 @@ class Request
* @param string $rewriteUrl * @param string $rewriteUrl
* @return static * @return static
*/ */
public function setRewriteUrl($rewriteUrl) public function setRewriteUrl(string $rewriteUrl): self
{ {
$this->hasRewrite = true; $this->hasRewrite = true;
$this->rewriteUrl = rtrim($rewriteUrl, '/') . '/'; $this->rewriteUrl = rtrim($rewriteUrl, '/') . '/';
@@ -286,10 +286,10 @@ class Request
/** /**
* Set rewrite callback * Set rewrite callback
* @param string $callback * @param string|\Closure $callback
* @return static * @return static
*/ */
public function setRewriteCallback($callback) public function setRewriteCallback($callback): self
{ {
$this->hasRewrite = true; $this->hasRewrite = true;
@@ -300,37 +300,60 @@ class Request
* Get loaded route * Get loaded route
* @return ILoadableRoute|null * @return ILoadableRoute|null
*/ */
public function getLoadedRoute() public function getLoadedRoute(): ?ILoadableRoute
{ {
return $this->loadedRoute; return (\count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
} }
/** /**
* Set loaded route * Get all loaded routes
* *
* @param ILoadableRoute $route * @return array
*/
public function getLoadedRoutes(): array
{
return $this->loadedRoutes;
}
/**
* Set loaded routes
*
* @param array $routes
* @return static * @return static
*/ */
public function setLoadedRoute(ILoadableRoute $route) public function setLoadedRoutes(array $routes): self
{ {
$this->loadedRoute = $route; $this->loadedRoutes = $routes;
return $this; return $this;
} }
public function hasRewrite() /**
* Added loaded route
*
* @param ILoadableRoute $route
* @return static
*/
public function addLoadedRoute(ILoadableRoute $route): self
{
$this->loadedRoutes[] = $route;
return $this;
}
public function hasRewrite(): bool
{ {
return $this->hasRewrite; return $this->hasRewrite;
} }
public function setHasRewrite($value) public function setHasRewrite($value): self
{ {
$this->hasRewrite = $value; $this->hasRewrite = $value;
return $this; return $this;
} }
public function isRewrite($url) public function isRewrite($url): bool
{ {
return ($this->rewriteUrl === $url); return ($this->rewriteUrl === $url);
} }
@@ -347,7 +370,7 @@ class Request
public function __get($name) public function __get($name)
{ {
return isset($this->data[$name]) ? $this->data[$name] : null; return $this->data[$name] ?? null;
} }
} }
+10 -11
View File
@@ -19,7 +19,7 @@ class Response
* @param int $code * @param int $code
* @return static * @return static
*/ */
public function httpCode($code) public function httpCode($code): self
{ {
http_response_code($code); http_response_code($code);
@@ -32,7 +32,7 @@ class Response
* @param string $url * @param string $url
* @param int $httpCode * @param int $httpCode
*/ */
public function redirect($url, $httpCode = null) public function redirect($url, $httpCode = null): void
{ {
if ($httpCode !== null) { if ($httpCode !== null) {
$this->httpCode($httpCode); $this->httpCode($httpCode);
@@ -42,7 +42,7 @@ class Response
exit(0); exit(0);
} }
public function refresh() public function refresh(): void
{ {
$this->redirect($this->request->getUrl()->getOriginalUrl()); $this->redirect($this->request->getUrl()->getOriginalUrl());
} }
@@ -52,7 +52,7 @@ class Response
* @param string $name * @param string $name
* @return static * @return static
*/ */
public function auth($name = '') public function auth($name = ''): self
{ {
$this->headers([ $this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"', 'WWW-Authenticate: Basic realm="' . $name . '"',
@@ -62,7 +62,7 @@ class Response
return $this; return $this;
} }
public function cache($eTag, $lastModified = 2592000) public function cache($eTag, $lastModified = 2592000): self
{ {
$this->headers([ $this->headers([
@@ -77,8 +77,7 @@ class Response
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) { if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) {
$this->header('HTTP/1.1 304 Not Modified'); $this->header('HTTP/1.1 304 Not Modified');
exit(0);
exit();
} }
return $this; return $this;
@@ -91,9 +90,9 @@ class Response
* @param int $dept JSON debt. * @param int $dept JSON debt.
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function json($value, $options = null, $dept = 512) public function json($value, $options = null, $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.');
} }
@@ -107,7 +106,7 @@ class Response
* @param string $value * @param string $value
* @return static * @return static
*/ */
public function header($value) public function header($value): self
{ {
header($value); header($value);
@@ -119,7 +118,7 @@ class Response
* @param array $headers * @param array $headers
* @return static * @return static
*/ */
public function headers(array $headers) public function headers(array $headers): self
{ {
foreach ($headers as $header) { foreach ($headers as $header) {
$this->header($header); $this->header($header);
+11 -22
View File
@@ -6,7 +6,7 @@ use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider class CookieTokenProvider implements ITokenProvider
{ {
const CSRF_KEY = 'CSRF-TOKEN'; public const CSRF_KEY = 'CSRF-TOKEN';
protected $token; protected $token;
protected $cookieTimeoutMinutes = 120; protected $cookieTimeoutMinutes = 120;
@@ -30,33 +30,22 @@ class CookieTokenProvider implements ITokenProvider
* @return string * @return string
* @throws SecurityException * @throws SecurityException
*/ */
public function generateToken() public function generateToken(): string
{ {
if (function_exists('random_bytes') === true) {
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());
} }
} }
$isSourceStrong = false;
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
if ($isSourceStrong === false || $random === false) {
throw new SecurityException('IV generation failed');
}
return $random;
}
/** /**
* Validate valid CSRF token * Validate valid CSRF token
* *
* @param string $token * @param string $token
* @return bool * @return bool
*/ */
public function validate($token) public function validate($token): bool
{ {
if ($token !== null && $this->getToken() !== null) { if ($token !== null && $this->getToken() !== null) {
return hash_equals($token, $this->getToken()); return hash_equals($token, $this->getToken());
@@ -71,7 +60,7 @@ class CookieTokenProvider implements ITokenProvider
* *
* @param string $token * @param string $token
*/ */
public function setToken($token) public function setToken($token): void
{ {
$this->token = $token; $this->token = $token;
setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/'); setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/');
@@ -82,17 +71,17 @@ class CookieTokenProvider implements ITokenProvider
* @param string|null $defaultValue * @param string|null $defaultValue
* @return string|null * @return string|null
*/ */
public function getToken($defaultValue = null) public function getToken($defaultValue = null): ?string
{ {
$this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null; $this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
return ($this->token !== null) ? $this->token : $defaultValue; return $this->token ?? $defaultValue;
} }
/** /**
* Refresh existing token * Refresh existing token
*/ */
public function refresh() public function refresh(): void
{ {
if ($this->token !== null) { if ($this->token !== null) {
$this->setToken($this->token); $this->setToken($this->token);
@@ -103,7 +92,7 @@ class CookieTokenProvider implements ITokenProvider
* Returns whether the csrf token has been defined * Returns whether the csrf token has been defined
* @return bool * @return bool
*/ */
public function hasToken() public function hasToken(): bool
{ {
return isset($_COOKIE[static::CSRF_KEY]); return isset($_COOKIE[static::CSRF_KEY]);
} }
@@ -112,7 +101,7 @@ class CookieTokenProvider implements ITokenProvider
* Get timeout for cookie in minutes * Get timeout for cookie in minutes
* @return int * @return int
*/ */
public function getCookieTimeoutMinutes() public function getCookieTimeoutMinutes(): int
{ {
return $this->cookieTimeoutMinutes; return $this->cookieTimeoutMinutes;
} }
@@ -121,7 +110,7 @@ class CookieTokenProvider implements ITokenProvider
* Set cookie timeout in minutes * Set cookie timeout in minutes
* @param $minutes * @param $minutes
*/ */
public function setCookieTimeoutMinutes($minutes) public function setCookieTimeoutMinutes($minutes): void
{ {
$this->cookieTimeoutMinutes = $minutes; $this->cookieTimeoutMinutes = $minutes;
} }
+10 -2
View File
@@ -8,7 +8,7 @@ interface ITokenProvider
/** /**
* Refresh existing token * Refresh existing token
*/ */
public function refresh(); public function refresh(): void;
/** /**
* Validate valid CSRF token * Validate valid CSRF token
@@ -16,6 +16,14 @@ interface ITokenProvider
* @param string $token * @param string $token
* @return bool * @return bool
*/ */
public function validate($token); public function validate($token): bool;
/**
* Get token token
*
* @param string|null $defaultValue
* @return string|null
*/
public function getToken($defaultValue = null);
} }
+18 -13
View File
@@ -38,7 +38,7 @@ class Url
* Check if url is using a secure protocol like https * Check if url is using a secure protocol like https
* @return bool * @return bool
*/ */
public function isSecure() public function isSecure(): bool
{ {
return (strtolower($this->getScheme()) === 'https'); return (strtolower($this->getScheme()) === 'https');
} }
@@ -47,7 +47,7 @@ class Url
* Checks if url is relative * Checks if url is relative
* @return bool * @return bool
*/ */
public function isRelative() public function isRelative(): bool
{ {
return ($this->getHost() === null); return ($this->getHost() === null);
} }
@@ -56,7 +56,7 @@ class Url
* Get url scheme * Get url scheme
* @return string|null * @return string|null
*/ */
public function getScheme() public function getScheme(): ?string
{ {
return $this->data['scheme']; return $this->data['scheme'];
} }
@@ -65,7 +65,7 @@ class Url
* Get url host * Get url host
* @return string|null * @return string|null
*/ */
public function getHost() public function getHost(): ?string
{ {
return $this->data['host']; return $this->data['host'];
} }
@@ -74,7 +74,7 @@ class Url
* Get url port * Get url port
* @return int|null * @return int|null
*/ */
public function getPort() public function getPort(): ?int
{ {
return ($this->data['port'] !== null) ? (int)$this->data['port'] : null; return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
} }
@@ -83,7 +83,7 @@ class Url
* Parse username from url * Parse username from url
* @return string|null * @return string|null
*/ */
public function getUserName() public function getUserName(): ?string
{ {
return $this->data['user']; return $this->data['user'];
} }
@@ -92,7 +92,7 @@ class Url
* Parse password from url * Parse password from url
* @return string|null * @return string|null
*/ */
public function getPassword() public function getPassword(): ?string
{ {
return $this->data['pass']; return $this->data['pass'];
} }
@@ -101,7 +101,7 @@ class Url
* Get path from url * Get path from url
* @return string * @return string
*/ */
public function getPath() public function getPath(): ?string
{ {
return $this->data['path']; return $this->data['path'];
} }
@@ -110,7 +110,7 @@ class Url
* Get querystring from url * Get querystring from url
* @return string|null * @return string|null
*/ */
public function getQueryString() public function getQueryString(): ?string
{ {
return $this->data['query']; return $this->data['query'];
} }
@@ -119,7 +119,7 @@ class Url
* Get fragment from url (everything after #) * Get fragment from url (everything after #)
* @return string|null * @return string|null
*/ */
public function getFragment() public function getFragment(): ?string
{ {
return $this->data['fragment']; return $this->data['fragment'];
} }
@@ -127,7 +127,7 @@ class Url
/** /**
* @return string * @return string
*/ */
public function getOriginalUrl() public function getOriginalUrl(): string
{ {
return $this->originalUrl; return $this->originalUrl;
} }
@@ -139,7 +139,7 @@ class Url
* @throws MalformedUrlException * @throws MalformedUrlException
* @return array * @return array
*/ */
public function parseUrl($url, $component = -1) public function parseUrl($url, $component = -1): array
{ {
$encodedUrl = preg_replace_callback( $encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u', '/[^:\/@?&=#]+/u',
@@ -158,11 +158,16 @@ class Url
return array_map('urldecode', $parts); return array_map('urldecode', $parts);
} }
public function contains($value): bool
{
return (stripos($this->getOriginalUrl(), $value) === false);
}
/** /**
* Returns data array with information about the url * Returns data array with information about the url
* @return array * @return array
*/ */
public function getData() public function getData(): array
{ {
return $this->data; return $this->data;
} }
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -9,7 +10,6 @@ interface IRouterBootManager
* Called when router loads it's routes * Called when router loads it's routes
* *
* @param Request $request * @param Request $request
* @return Request
*/ */
public function boot(Request $request); public function boot(Request $request): void;
} }
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter\Route; namespace Pecee\SimpleRouter\Route;
interface IControllerRoute extends IRoute interface IControllerRoute extends IRoute
@@ -8,7 +9,7 @@ interface IControllerRoute extends IRoute
* *
* @return string * @return string
*/ */
public function getController(); public function getController(): string;
/** /**
* Set controller class-name * Set controller class-name
@@ -16,21 +17,6 @@ interface IControllerRoute extends IRoute
* @param string $controller * @param string $controller
* @return static * @return static
*/ */
public function setController($controller); public function setController($controller): self;
/**
* Return active method
*
* @return string
*/
public function getMethod();
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method);
} }
+9 -9
View File
@@ -13,7 +13,7 @@ interface IGroupRoute extends IRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchDomain(Request $request); public function matchDomain(Request $request): bool;
/** /**
* Add exception handler * Add exception handler
@@ -36,35 +36,35 @@ interface IGroupRoute extends IRoute
* *
* @return array * @return array
*/ */
public function getExceptionHandlers(); public function getExceptionHandlers(): array;
/** /**
* Get domains for domain. * Get domains for domain.
* *
* @return array * @return array
*/ */
public function getDomains(); public function getDomains(): array;
/** /**
* Set allowed domains for group. * Set allowed domains for group.
* *
* @param array $domains * @param array $domains
* @return $this * @return static
*/ */
public function setDomains(array $domains); public function setDomains(array $domains): self;
/** /**
* Set prefix that child-routes will inherit. * Set prefix that child-routes will inherit.
* *
* @param string $prefix * @param string $prefix
* @return string * @return static
*/ */
public function setPrefix($prefix); public function setPrefix($prefix): self;
/** /**
* Get prefix. * Get prefix.
* *
* @return string * @return string|null
*/ */
public function getPrefix(); public function getPrefix(): ?string;
} }
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter\Route; namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -14,7 +15,7 @@ interface ILoadableRoute extends IRoute
* @param string|null $name * @param string|null $name
* @return string * @return string
*/ */
public function findUrl($method = null, $parameters = null, $name = null); public function findUrl($method = null, $parameters = null, $name = null): string;
/** /**
* Loads and renders middlewares-classes * Loads and renders middlewares-classes
@@ -30,9 +31,9 @@ interface ILoadableRoute extends IRoute
/** /**
* Returns the provided name for the router. * Returns the provided name for the router.
* *
* @return string * @return string|null
*/ */
public function getName(); public function getName(): string;
/** /**
* Check if route has given name. * Check if route has given name.
@@ -40,22 +41,22 @@ interface ILoadableRoute extends IRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name); public function hasName($name): bool;
/** /**
* Sets the router name, which makes it easier to obtain the url or router at a later point. * Sets the router name, which makes it easier to obtain the url or router at a later point.
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name); public function setName($name): self;
/** /**
* Get regular expression match used for matching route (if defined). * Get regular expression match used for matching route (if defined).
* *
* @return string * @return string
*/ */
public function getMatch(); public function getMatch(): string;
/** /**
* Add regular expression match for the entire route. * Add regular expression match for the entire route.
@@ -63,6 +64,6 @@ interface ILoadableRoute extends IRoute
* @param string $regex * @param string $regex
* @return static * @return static
*/ */
public function setMatch($regex); public function setMatch($regex): self;
} }
+39 -28
View File
@@ -13,7 +13,7 @@ interface IRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchRoute($route, Request $request); public function matchRoute($route, Request $request): bool;
/** /**
* Called when route is matched. * Called when route is matched.
@@ -23,7 +23,7 @@ interface IRoute
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return string * @return string
*/ */
public function renderRoute(Request $request); public function renderRoute(Request $request): ?string;
/** /**
* Returns callback name/identifier for the current route based on the callback. * Returns callback name/identifier for the current route based on the callback.
@@ -32,50 +32,50 @@ interface IRoute
* *
* @return string * @return string
*/ */
public function getIdentifier(); public function getIdentifier(): string;
/** /**
* Set allowed request methods * Set allowed request methods
* *
* @param array $methods * @param array $methods
* @return static $this * @return static
*/ */
public function setRequestMethods(array $methods); public function setRequestMethods(array $methods): self;
/** /**
* Get allowed request methods * Get allowed request methods
* *
* @return array * @return array
*/ */
public function getRequestMethods(); public function getRequestMethods(): array;
/** /**
* @return IRoute|null * @return IRoute|null
*/ */
public function getParent(); public function getParent(): ?IRoute;
/** /**
* Get the group for the route. * Get the group for the route.
* *
* @return IGroupRoute|null * @return IGroupRoute|null
*/ */
public function getGroup(); public function getGroup(): ?IGroupRoute;
/** /**
* Set group * Set group
* *
* @param IGroupRoute $group * @param IGroupRoute $group
* @return static $this * @return static
*/ */
public function setGroup(IGroupRoute $group); public function setGroup(IGroupRoute $group): self;
/** /**
* Set parent route * Set parent route
* *
* @param IRoute $parent * @param IRoute $parent
* @return static $this * @return static
*/ */
public function setParent(IRoute $parent); public function setParent(IRoute $parent): self;
/** /**
* Set callback * Set callback
@@ -83,33 +83,44 @@ interface IRoute
* @param string $callback * @param string $callback
* @return static * @return static
*/ */
public function setCallback($callback); public function setCallback($callback): self;
/** /**
* @return string * @return string|callable
*/ */
public function getCallback(); public function getCallback();
public function getMethod(); /**
* Return active method
*
* @return string|null
*/
public function getMethod(): ?string;
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method): self;
public function getClass(); public function getClass();
public function setMethod($method);
/** /**
* @param string $namespace * @param string $namespace
* @return static $this * @return static
*/ */
public function setNamespace($namespace); public function setNamespace($namespace);
/** /**
* @return string * @return string|null
*/ */
public function getNamespace(); public function getNamespace(): ?string;
/** /**
* @param string $namespace * @param string $namespace
* @return static $this * @return static
*/ */
public function setDefaultNamespace($namespace); public function setDefaultNamespace($namespace);
@@ -120,7 +131,7 @@ interface IRoute
* *
* @return array * @return array
*/ */
public function getWhere(); public function getWhere(): array;
/** /**
* Set parameter names. * Set parameter names.
@@ -135,7 +146,7 @@ interface IRoute
* *
* @return array * @return array
*/ */
public function getParameters(); public function getParameters(): array;
/** /**
* Get parameters * Get parameters
@@ -159,14 +170,14 @@ interface IRoute
* *
* @return array * @return array
*/ */
public function toArray(); public function toArray(): array;
/** /**
* Get middlewares array * Get middlewares array
* *
* @return array * @return array
*/ */
public function getMiddlewares(); public function getMiddlewares(): array;
/** /**
* Set middleware class-name * Set middleware class-name
@@ -174,14 +185,14 @@ interface IRoute
* @param string $middleware * @param string $middleware
* @return static * @return static
*/ */
public function addMiddleware($middleware); public function addMiddleware($middleware): self;
/** /**
* Set middlewares array * Set middlewares array
* *
* @param array $middlewares * @param array $middlewares
* @return $this * @return static
*/ */
public function setMiddlewares(array $middlewares); public function setMiddlewares(array $middlewares): self;
} }
+17 -17
View File
@@ -26,11 +26,11 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param Request $request * @param Request $request
* @throws HttpException * @throws HttpException
*/ */
public function loadMiddleware(Request $request) public function loadMiddleware(Request $request) : void
{ {
foreach ($this->getMiddlewares() as $middleware) { foreach ($this->getMiddlewares() as $middleware) {
if (is_object($middleware) === false) { if (\is_object($middleware) === false) {
$middleware = $this->loadClass($middleware); $middleware = $this->loadClass($middleware);
} }
@@ -42,7 +42,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
} }
} }
public function matchRegex(Request $request, $url) public function matchRegex(Request $request, $url) : ?bool
{ {
/* Match on custom defined regular expression */ /* Match on custom defined regular expression */
@@ -59,7 +59,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $url * @param string $url
* @return static * @return static
*/ */
public function setUrl($url) public function setUrl($url) : self
{ {
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/'; $this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
@@ -75,7 +75,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return $this; return $this;
} }
public function getUrl() public function getUrl() : string
{ {
return $this->url; return $this->url;
} }
@@ -89,13 +89,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|null $name * @param string|null $name
* @return string * @return string
*/ */
public function findUrl($method = null, $parameters = null, $name = null) public function findUrl($method = null, $parameters = null, $name = null) : string
{ {
$url = $this->getUrl(); $url = $this->getUrl();
$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;
} }
@@ -114,7 +114,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;
@@ -144,7 +144,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* *
* @return string * @return string
*/ */
public function getName() public function getName() : string
{ {
return $this->name; return $this->name;
} }
@@ -155,9 +155,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name) public function hasName($name) : bool
{ {
return (strtolower($this->name) === strtolower($name)); return strtolower($this->name) === strtolower($name);
} }
/** /**
@@ -166,7 +166,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $regex * @param string $regex
* @return static * @return static
*/ */
public function setMatch($regex) public function setMatch($regex) : ILoadableRoute
{ {
$this->regex = $regex; $this->regex = $regex;
@@ -178,7 +178,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* *
* @return string * @return string
*/ */
public function getMatch() public function getMatch() : string
{ {
return $this->regex; return $this->regex;
} }
@@ -191,7 +191,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|array $name * @param string|array $name
* @return static * @return static
*/ */
public function name($name) public function name($name) : ILoadableRoute
{ {
return $this->setName($name); return $this->setName($name);
} }
@@ -200,9 +200,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Sets the router name, which makes it easier to obtain the url or router at a later point. * Sets the router name, which makes it easier to obtain the url or router at a later point.
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name) public function setName($name) : ILoadableRoute
{ {
$this->name = $name; $this->name = $name;
@@ -216,7 +216,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, $merge = false): IRoute
{ {
if (isset($values['as']) === true) { if (isset($values['as']) === true) {
+48 -48
View File
@@ -8,15 +8,15 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
abstract class Route implements IRoute abstract class Route implements IRoute
{ {
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s'; protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
const PARAMETERS_DEFAULT_REGEX = '[\w]+'; protected const PARAMETERS_DEFAULT_REGEX = '[\w]+';
const REQUEST_TYPE_GET = 'get'; public const REQUEST_TYPE_GET = 'get';
const REQUEST_TYPE_POST = 'post'; public const REQUEST_TYPE_POST = 'post';
const REQUEST_TYPE_PUT = 'put'; public const REQUEST_TYPE_PUT = 'put';
const REQUEST_TYPE_PATCH = 'patch'; public const REQUEST_TYPE_PATCH = 'patch';
const REQUEST_TYPE_OPTIONS = 'options'; public const REQUEST_TYPE_OPTIONS = 'options';
const REQUEST_TYPE_DELETE = 'delete'; public const REQUEST_TYPE_DELETE = 'delete';
public static $requestTypes = [ public static $requestTypes = [
self::REQUEST_TYPE_GET, self::REQUEST_TYPE_GET,
@@ -75,10 +75,10 @@ abstract class Route implements IRoute
* Render route * Render route
* *
* @param Request $request * @param Request $request
* @return string|mixed * @return string|null
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function renderRoute(Request $request) public function renderRoute(Request $request): ?string
{ {
$callback = $this->getCallback(); $callback = $this->getCallback();
@@ -97,9 +97,9 @@ abstract class Route implements IRoute
} }
/* Render callback function */ /* Render callback function */
if (is_callable($callback) === true) { if (\is_callable($callback) === true) {
/* When the callback is a function */ /* When the callback is a function */
return call_user_func_array($callback, $parameters); return \call_user_func_array($callback, $parameters);
} }
/* When the callback is a class + method */ /* When the callback is a class + method */
@@ -116,7 +116,7 @@ abstract class Route implements IRoute
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404); throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
} }
return call_user_func_array([$class, $method], $parameters); return \call_user_func_array([$class, $method], $parameters);
} }
protected function parseParameters($route, $url, $parameterRegex = null) protected function parseParameters($route, $url, $parameterRegex = null)
@@ -138,7 +138,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];
@@ -151,7 +151,7 @@ abstract class Route implements IRoute
if ($parameterRegex !== null) { if ($parameterRegex !== null) {
$regex = $parameterRegex; $regex = $parameterRegex;
} else { } else {
$regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex; $regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
} }
} }
@@ -189,9 +189,9 @@ abstract class Route implements IRoute
* *
* @return string * @return string
*/ */
public function getIdentifier() 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;
} }
@@ -202,9 +202,9 @@ abstract class Route implements IRoute
* Set allowed request methods * Set allowed request methods
* *
* @param array $methods * @param array $methods
* @return static $this * @return static
*/ */
public function setRequestMethods(array $methods) public function setRequestMethods(array $methods): IRoute
{ {
$this->requestMethods = $methods; $this->requestMethods = $methods;
@@ -216,7 +216,7 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function getRequestMethods() public function getRequestMethods(): array
{ {
return $this->requestMethods; return $this->requestMethods;
} }
@@ -224,7 +224,7 @@ abstract class Route implements IRoute
/** /**
* @return IRoute|null * @return IRoute|null
*/ */
public function getParent() public function getParent(): ?IRoute
{ {
return $this->parent; return $this->parent;
} }
@@ -234,7 +234,7 @@ abstract class Route implements IRoute
* *
* @return IGroupRoute|null * @return IGroupRoute|null
*/ */
public function getGroup() public function getGroup(): ?IGroupRoute
{ {
return $this->group; return $this->group;
} }
@@ -243,9 +243,9 @@ abstract class Route implements IRoute
* Set group * Set group
* *
* @param IGroupRoute $group * @param IGroupRoute $group
* @return static $this * @return static
*/ */
public function setGroup(IGroupRoute $group) public function setGroup(IGroupRoute $group): IRoute
{ {
$this->group = $group; $this->group = $group;
@@ -259,9 +259,9 @@ abstract class Route implements IRoute
* Set parent route * Set parent route
* *
* @param IRoute $parent * @param IRoute $parent
* @return static $this * @return static
*/ */
public function setParent(IRoute $parent) public function setParent(IRoute $parent): IRoute
{ {
$this->parent = $parent; $this->parent = $parent;
@@ -274,7 +274,7 @@ abstract class Route implements IRoute
* @param string $callback * @param string $callback
* @return static * @return static
*/ */
public function setCallback($callback) public function setCallback($callback): IRoute
{ {
$this->callback = $callback; $this->callback = $callback;
@@ -282,16 +282,16 @@ abstract class Route implements IRoute
} }
/** /**
* @return string * @return string|callable
*/ */
public function getCallback() public function getCallback()
{ {
return $this->callback; return $this->callback;
} }
public function getMethod() public function getMethod(): ?string
{ {
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];
@@ -302,7 +302,7 @@ abstract class Route implements IRoute
public function getClass() public function getClass()
{ {
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];
@@ -311,7 +311,7 @@ abstract class Route implements IRoute
return null; return null;
} }
public function setMethod($method) public function setMethod($method): IRoute
{ {
$this->callback = sprintf('%s@%s', $this->getClass(), $method); $this->callback = sprintf('%s@%s', $this->getClass(), $method);
@@ -353,11 +353,11 @@ abstract class Route implements IRoute
} }
/** /**
* @return string * @return string|null
*/ */
public function getNamespace() public function getNamespace(): ?string
{ {
return ($this->namespace === null) ? $this->defaultNamespace : $this->namespace; return $this->namespace ?? $this->defaultNamespace;
} }
/** /**
@@ -365,7 +365,7 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function toArray() public function toArray(): array
{ {
$values = []; $values = [];
@@ -373,15 +373,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;
} }
@@ -434,7 +434,7 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function getWhere() public function getWhere(): array
{ {
return $this->where; return $this->where;
} }
@@ -470,12 +470,12 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function getParameters() public function getParameters(): array
{ {
/* 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;
} }
@@ -494,7 +494,7 @@ abstract class Route implements IRoute
* If this is the first time setting parameters we store them so we * If this is the first time setting parameters we store them so we
* later can organize the array, in case somebody tried to sort the array. * later can organize the array, in case somebody tried to sort the array.
*/ */
if (count($parameters) !== 0 && count($this->originalParameters) === 0) { if (\count($parameters) !== 0 && \count($this->originalParameters) === 0) {
$this->originalParameters = $parameters; $this->originalParameters = $parameters;
} }
@@ -523,7 +523,7 @@ abstract class Route implements IRoute
* @param IMiddleware|string $middleware * @param IMiddleware|string $middleware
* @return static * @return static
*/ */
public function addMiddleware($middleware) public function addMiddleware($middleware): IRoute
{ {
$this->middlewares[] = $middleware; $this->middlewares[] = $middleware;
@@ -534,9 +534,9 @@ abstract class Route implements IRoute
* Set middlewares array * Set middlewares array
* *
* @param array $middlewares * @param array $middlewares
* @return $this * @return static
*/ */
public function setMiddlewares(array $middlewares) public function setMiddlewares(array $middlewares): IRoute
{ {
$this->middlewares = $middlewares; $this->middlewares = $middlewares;
@@ -546,7 +546,7 @@ abstract class Route implements IRoute
/** /**
* @return array * @return array
*/ */
public function getMiddlewares() public function getMiddlewares(): array
{ {
return $this->middlewares; return $this->middlewares;
} }
@@ -570,7 +570,7 @@ abstract class Route implements IRoute
* *
* @return string * @return string
*/ */
public function getDefaultParameterRegex() public function getDefaultParameterRegex(): string
{ {
return $this->defaultParameterRegex; return $this->defaultParameterRegex;
} }
@@ -24,7 +24,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name) public function hasName($name): bool
{ {
if ($this->name === null) { if ($this->name === null) {
return false; return false;
@@ -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, false) === true && strtolower($this->name) === strtolower($newName)) { if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
return true; return true;
} }
} }
@@ -49,7 +49,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string|null $name * @param string|null $name
* @return string * @return string
*/ */
public function findUrl($method = null, $parameters = null, $name = null) public function findUrl($method = null, $parameters = null, $name = null): string
{ {
if (strpos($name, '.') !== false) { if (strpos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false); $found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
@@ -67,7 +67,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
foreach (static::$requestTypes as $requestType) { foreach (static::$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];
} }
@@ -86,9 +86,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
return '/' . trim($url, '/') . '/'; return '/' . trim($url, '/') . '/';
} }
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) { if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false; return false;
} }
@@ -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);
@@ -123,7 +123,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* *
* @return string * @return string
*/ */
public function getController() public function getController(): string
{ {
return $this->controller; return $this->controller;
} }
@@ -134,7 +134,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $controller * @param string $controller
* @return static * @return static
*/ */
public function setController($controller) public function setController($controller): IControllerRoute
{ {
$this->controller = $controller; $this->controller = $controller;
@@ -144,9 +144,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
/** /**
* Return active method * Return active method
* *
* @return string * @return string|null
*/ */
public function getMethod() public function getMethod(): ?string
{ {
return $this->method; return $this->method;
} }
@@ -157,7 +157,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $method * @param string $method
* @return static * @return static
*/ */
public function setMethod($method) public function setMethod($method): IRoute
{ {
$this->method = $method; $this->method = $method;
@@ -171,7 +171,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, $merge = false): IRoute
{ {
if (isset($values['names']) === true) { if (isset($values['names']) === true) {
$this->names = $values['names']; $this->names = $values['names'];
+19 -19
View File
@@ -18,9 +18,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchDomain(Request $request) 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;
} }
@@ -28,7 +28,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;
@@ -46,9 +46,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) { if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false; return false;
} }
@@ -64,9 +64,9 @@ class RouteGroup extends Route implements IGroupRoute
* Add exception handler * Add exception handler
* *
* @param IExceptionHandler|string $handler * @param IExceptionHandler|string $handler
* @return static $this * @return static
*/ */
public function addExceptionHandler($handler) public function addExceptionHandler($handler): IGroupRoute
{ {
$this->exceptionHandlers[] = $handler; $this->exceptionHandlers[] = $handler;
@@ -77,9 +77,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set exception-handlers for group * Set exception-handlers for group
* *
* @param array $handlers * @param array $handlers
* @return static $this * @return static
*/ */
public function setExceptionHandlers(array $handlers) public function setExceptionHandlers(array $handlers): IGroupRoute
{ {
$this->exceptionHandlers = $handlers; $this->exceptionHandlers = $handlers;
@@ -91,7 +91,7 @@ class RouteGroup extends Route implements IGroupRoute
* *
* @return array * @return array
*/ */
public function getExceptionHandlers() public function getExceptionHandlers(): array
{ {
return $this->exceptionHandlers; return $this->exceptionHandlers;
} }
@@ -101,7 +101,7 @@ class RouteGroup extends Route implements IGroupRoute
* *
* @return array * @return array
*/ */
public function getDomains() public function getDomains(): array
{ {
return $this->domains; return $this->domains;
} }
@@ -110,9 +110,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set allowed domains for group. * Set allowed domains for group.
* *
* @param array $domains * @param array $domains
* @return $this * @return static
*/ */
public function setDomains(array $domains) public function setDomains(array $domains): IGroupRoute
{ {
$this->domains = $domains; $this->domains = $domains;
@@ -123,7 +123,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix * @param string $prefix
* @return static * @return static
*/ */
public function setPrefix($prefix) public function setPrefix($prefix): IGroupRoute
{ {
$this->prefix = '/' . trim($prefix, '/'); $this->prefix = '/' . trim($prefix, '/');
@@ -133,9 +133,9 @@ class RouteGroup extends Route implements IGroupRoute
/** /**
* Set prefix that child-routes will inherit. * Set prefix that child-routes will inherit.
* *
* @return string * @return string|null
*/ */
public function getPrefix() public function getPrefix(): ?string
{ {
return $this->prefix; return $this->prefix;
} }
@@ -147,7 +147,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, $merge = false): IRoute
{ {
if (isset($values['prefix']) === true) { if (isset($values['prefix']) === true) {
@@ -183,7 +183,7 @@ class RouteGroup extends Route implements IGroupRoute
* *
* @return array * @return array
*/ */
public function toArray() public function toArray(): array
{ {
$values = []; $values = [];
@@ -195,7 +195,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;
} }
@@ -15,9 +15,9 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) { if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false; return false;
} }
+11 -11
View File
@@ -42,7 +42,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name) public function hasName($name): bool
{ {
if ($this->name === null) { if ($this->name === null) {
return false; return false;
@@ -60,7 +60,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return (strtolower($this->name) === strtolower($name)); return (strtolower($this->name) === strtolower($name));
} }
public function findUrl($method = null, $parameters = null, $name = null) public function findUrl($method = null, $parameters = null, $name = null): string
{ {
$url = array_search($name, $this->names, false); $url = array_search($name, $this->names, false);
if ($url !== false) { if ($url !== false) {
@@ -77,9 +77,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return true; return true;
} }
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) { if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false; return false;
} }
@@ -114,7 +114,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
} }
// Update // Update
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) { if ($id !== null && \in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], true) === true) {
return $this->call($this->methodNames['update']); return $this->call($this->methodNames['update']);
} }
@@ -145,7 +145,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/** /**
* @return string * @return string
*/ */
public function getController() public function getController(): string
{ {
return $this->controller; return $this->controller;
} }
@@ -154,14 +154,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $controller * @param string $controller
* @return static * @return static
*/ */
public function setController($controller) public function setController($controller): IControllerRoute
{ {
$this->controller = $controller; $this->controller = $controller;
return $this; return $this;
} }
public function setName($name) public function setName($name): ILoadableRoute
{ {
$this->name = $name; $this->name = $name;
@@ -194,9 +194,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/** /**
* Get method names * Get method names
* *
* @return array $this * @return array
*/ */
public function getMethodNames() public function getMethodNames(): array
{ {
return $this->methodNames; return $this->methodNames;
} }
@@ -208,7 +208,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, $merge = false): IRoute
{ {
if (isset($values['names']) === true) { if (isset($values['names']) === true) {
$this->names = $values['names']; $this->names = $values['names'];
+2 -2
View File
@@ -12,9 +12,9 @@ class RouteUrl extends LoadableRoute
$this->setCallback($callback); $this->setCallback($callback);
} }
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) { if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false; return false;
} }
+38 -38
View File
@@ -78,7 +78,7 @@ class Router
/** /**
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public function reset() public function reset() : void
{ {
$this->processingRoute = false; $this->processingRoute = false;
$this->request = new Request(); $this->request = new Request();
@@ -94,7 +94,7 @@ class Router
* @param IRoute $route * @param IRoute $route
* @return IRoute * @return IRoute
*/ */
public function addRoute(IRoute $route) public function addRoute(IRoute $route) : IRoute
{ {
/* /*
* If a route is currently being processed, that means that the route being added are rendered from the parent * If a route is currently being processed, that means that the route being added are rendered from the parent
@@ -115,13 +115,13 @@ class Router
* @param IRoute $route * @param IRoute $route
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
protected function renderAndProcess(IRoute $route) { protected function renderAndProcess(IRoute $route) : void {
$this->processingRoute = true; $this->processingRoute = true;
$route->renderRoute($this->request); $route->renderRoute($this->request);
$this->processingRoute = false; $this->processingRoute = 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;
@@ -139,7 +139,7 @@ class Router
* @param IGroupRoute|null $group * @param IGroupRoute|null $group
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
protected function processRoutes(array $routes, IGroupRoute $group = null) protected function processRoutes(array $routes, IGroupRoute $group = null) : void
{ {
// Loop through each route-request // Loop through each route-request
$exceptionHandlers = []; $exceptionHandlers = [];
@@ -149,7 +149,7 @@ class Router
return; return;
} }
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath(); $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route IRoute */ /* @var $route IRoute */
foreach ($routes as $route) { foreach ($routes as $route) {
@@ -165,7 +165,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();
} }
@@ -199,7 +199,7 @@ class Router
* @throws NotFoundHttpException * @throws NotFoundHttpException
* @return void * @return void
*/ */
public function loadRoutes() public function loadRoutes() : void
{ {
/* Initialize boot-managers */ /* Initialize boot-managers */
/* @var $manager IRouterBootManager */ /* @var $manager IRouterBootManager */
@@ -215,11 +215,11 @@ class Router
* Routes the request * Routes the request
* *
* @param bool $rewrite * @param bool $rewrite
* @return string|mixed * @return string|null
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws \Exception
*/ */
public function routeRequest($rewrite = false) public function routeRequest($rewrite = false) : ?string
{ {
$routeNotAllowed = false; $routeNotAllowed = false;
@@ -237,7 +237,7 @@ class Router
$this->request->setHasRewrite(false); $this->request->setHasRewrite(false);
} }
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath(); $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route ILoadableRoute */ /* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $key => $route) { foreach ($this->processedRoutes as $key => $route) {
@@ -246,7 +246,7 @@ class Router
if ($route->matchRoute($url, $this->request) === true) { if ($route->matchRoute($url, $this->request) === true) {
/* Check if request method matches */ /* Check if request method matches */
if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) { if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$routeNotAllowed = true; $routeNotAllowed = true;
continue; continue;
} }
@@ -262,7 +262,7 @@ class Router
/* Render route */ /* Render route */
$routeNotAllowed = false; $routeNotAllowed = false;
$this->request->setLoadedRoute($route); $this->request->addLoadedRoute($route);
$output = $route->renderRoute($this->request); $output = $route->renderRoute($this->request);
@@ -287,7 +287,7 @@ class Router
$this->handleException(new HttpException($message, 403)); $this->handleException(new HttpException($message, 403));
} }
if ($this->request->getLoadedRoute() === null) { if (\count($this->request->getLoadedRoutes()) === 0) {
$rewriteUrl = $this->request->getRewriteUrl(); $rewriteUrl = $this->request->getRewriteUrl();
@@ -303,7 +303,7 @@ class Router
return null; return null;
} }
protected function hasRewrite($url) protected function hasRewrite($url) : bool
{ {
/* If the request has changed */ /* If the request has changed */
@@ -332,14 +332,14 @@ class Router
* @param \Exception $e * @param \Exception $e
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws \Exception
* @return string * @return string|null
*/ */
protected function handleException(\Exception $e) protected function handleException(\Exception $e) : ?string
{ {
/* @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();
} }
@@ -366,9 +366,9 @@ class Router
throw $e; throw $e;
} }
public function arrayToParams(array $getParams = [], $includeEmpty = true) public function arrayToParams(array $getParams = [], $includeEmpty = true) : string
{ {
if (count($getParams) !== 0) { if (\count($getParams) !== 0) {
if ($includeEmpty === false) { if ($includeEmpty === false) {
$getParams = array_filter($getParams, function ($item) { $getParams = array_filter($getParams, function ($item) {
@@ -388,13 +388,13 @@ class Router
* @param string $name * @param string $name
* @return ILoadableRoute|null * @return ILoadableRoute|null
*/ */
public function findRoute($name) public function findRoute($name) : ?ILoadableRoute
{ {
/* @var $route ILoadableRoute */ /* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) { foreach ($this->processedRoutes as $route) {
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */ /* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
if ($route->hasName($name)) { if ($route->hasName($name) === true) {
return $route; return $route;
} }
@@ -404,8 +404,8 @@ 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) {
list($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())) {
return $route; return $route;
@@ -413,7 +413,7 @@ class Router
} }
/* Check if callback matches (if it's not a function) */ /* Check if callback matches (if it's not a function) */
if (is_string($name) === true && is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && is_callable($route->getCallback()) === false) { if (\is_string($name) === true && \is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && \is_callable($route->getCallback()) === false) {
/* Check if the entire callback is matching */ /* Check if the entire callback is matching */
if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) { if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) {
@@ -448,9 +448,9 @@ class Router
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return string * @return string
*/ */
public function getUrl($name = null, $parameters = null, $getParams = null) public function getUrl($name = null, $parameters = null, $getParams = null) : string
{ {
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');
} }
@@ -485,8 +485,8 @@ 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) {
list($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 */
@@ -516,7 +516,7 @@ class Router
* Get bootmanagers * Get bootmanagers
* @return array * @return array
*/ */
public function getBootManagers() public function getBootManagers() : array
{ {
return $this->bootManagers; return $this->bootManagers;
} }
@@ -525,7 +525,7 @@ class Router
* Set bootmanagers * Set bootmanagers
* @param array $bootManagers * @param array $bootManagers
*/ */
public function setBootManagers(array $bootManagers) public function setBootManagers(array $bootManagers) : void
{ {
$this->bootManagers = $bootManagers; $this->bootManagers = $bootManagers;
} }
@@ -534,7 +534,7 @@ class Router
* Add bootmanager * Add bootmanager
* @param IRouterBootManager $bootManager * @param IRouterBootManager $bootManager
*/ */
public function addBootManager(IRouterBootManager $bootManager) public function addBootManager(IRouterBootManager $bootManager) : void
{ {
$this->bootManagers[] = $bootManager; $this->bootManagers[] = $bootManager;
} }
@@ -544,7 +544,7 @@ class Router
* *
* @return array * @return array
*/ */
public function getProcessedRoutes() public function getProcessedRoutes() : array
{ {
return $this->processedRoutes; return $this->processedRoutes;
} }
@@ -552,7 +552,7 @@ class Router
/** /**
* @return array * @return array
*/ */
public function getRoutes() public function getRoutes() : array
{ {
return $this->routes; return $this->routes;
} }
@@ -561,9 +561,9 @@ class Router
* Set routes * Set routes
* *
* @param array $routes * @param array $routes
* @return static $this * @return static
*/ */
public function setRoutes(array $routes) public function setRoutes(array $routes) : self
{ {
$this->routes = $routes; $this->routes = $routes;
@@ -575,7 +575,7 @@ class Router
* *
* @return Request * @return Request
*/ */
public function getRequest() public function getRequest() : Request
{ {
return $this->request; return $this->request;
} }
@@ -584,7 +584,7 @@ class Router
* Get csrf verifier class * Get csrf verifier class
* @return BaseCsrfVerifier * @return BaseCsrfVerifier
*/ */
public function getCsrfVerifier() public function getCsrfVerifier() : BaseCsrfVerifier
{ {
return $this->csrfVerifier; return $this->csrfVerifier;
} }
+53 -31
View File
@@ -13,12 +13,15 @@ namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\CallbackExceptionHandler; use Pecee\Handlers\CallbackExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier; use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response; use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException; use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Route\IGroupRoute;
use Pecee\SimpleRouter\Route\IPartialGroupRoute;
use Pecee\SimpleRouter\Route\IRoute; use Pecee\SimpleRouter\Route\IRoute;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteController; use Pecee\SimpleRouter\Route\RouteController;
use Pecee\SimpleRouter\Route\RouteGroup; use Pecee\SimpleRouter\Route\RouteGroup;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteResource; use Pecee\SimpleRouter\Route\RouteResource;
use Pecee\SimpleRouter\Route\RouteUrl; use Pecee\SimpleRouter\Route\RouteUrl;
@@ -26,7 +29,7 @@ class SimpleRouter
{ {
/** /**
* Default namespace added to all routes * Default namespace added to all routes
* @var string * @var string|null
*/ */
protected static $defaultNamespace; protected static $defaultNamespace;
@@ -47,17 +50,36 @@ class SimpleRouter
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws \Exception
*/ */
public static function start() public static function start(): void
{ {
echo static::router()->routeRequest(); echo static::router()->routeRequest();
} }
/**
* Get debug info array
*
* @return array
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function debugInfo(): array
{
return [
'url' => static::request()->getUrl(),
'method' => static::request()->getMethod(),
'host' => static::request()->getHost(),
'loaded_routes' => static::request()->getLoadedRoutes(),
'all_routes' => static::router()->getRoutes(),
'boot_managers' => static::router()->getBootManagers(),
'csrf_verifier' => static::router()->getCsrfVerifier(),
];
}
/** /**
* Set default namespace which will be prepended to all routes. * Set default namespace which will be prepended to all routes.
* *
* @param string $defaultNamespace * @param string $defaultNamespace
*/ */
public static function setDefaultNamespace($defaultNamespace) public static function setDefaultNamespace(string $defaultNamespace): void
{ {
static::$defaultNamespace = $defaultNamespace; static::$defaultNamespace = $defaultNamespace;
} }
@@ -68,7 +90,7 @@ class SimpleRouter
* @param BaseCsrfVerifier $baseCsrfVerifier * @param BaseCsrfVerifier $baseCsrfVerifier
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier): void
{ {
static::router()->setCsrfVerifier($baseCsrfVerifier); static::router()->setCsrfVerifier($baseCsrfVerifier);
} }
@@ -80,7 +102,7 @@ class SimpleRouter
* @param IRouterBootManager $bootManager * @param IRouterBootManager $bootManager
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function addBootManager(IRouterBootManager $bootManager) public static function addBootManager(IRouterBootManager $bootManager): void
{ {
static::router()->addBootManager($bootManager); static::router()->addBootManager($bootManager);
} }
@@ -95,7 +117,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function get($url, $callback, array $settings = null) public static function get(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['get'], $url, $callback, $settings); return static::match(['get'], $url, $callback, $settings);
} }
@@ -109,7 +131,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function post($url, $callback, array $settings = null) public static function post(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['post'], $url, $callback, $settings); return static::match(['post'], $url, $callback, $settings);
} }
@@ -123,7 +145,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function put($url, $callback, array $settings = null) public static function put(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['put'], $url, $callback, $settings); return static::match(['put'], $url, $callback, $settings);
} }
@@ -137,7 +159,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function patch($url, $callback, array $settings = null) public static function patch(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['patch'], $url, $callback, $settings); return static::match(['patch'], $url, $callback, $settings);
} }
@@ -151,7 +173,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function options($url, $callback, array $settings = null) public static function options(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['options'], $url, $callback, $settings); return static::match(['options'], $url, $callback, $settings);
} }
@@ -165,7 +187,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function delete($url, $callback, array $settings = null) public static function delete(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['delete'], $url, $callback, $settings); return static::match(['delete'], $url, $callback, $settings);
} }
@@ -179,9 +201,9 @@ class SimpleRouter
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function group(array $settings = [], \Closure $callback) 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');
} }
@@ -205,9 +227,9 @@ class SimpleRouter
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function partialGroup($url, \Closure $callback, array $settings = []) 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');
} }
@@ -232,7 +254,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function basic($url, $callback, array $settings = null) public static function basic(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['get', 'post'], $url, $callback, $settings); return static::match(['get', 'post'], $url, $callback, $settings);
} }
@@ -248,7 +270,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function form($url, $callback, array $settings = null) public static function form(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['get', 'post'], $url, $callback, $settings); return static::match(['get', 'post'], $url, $callback, $settings);
} }
@@ -263,7 +285,7 @@ class SimpleRouter
* @return RouteUrl|IRoute * @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function match(array $requestMethods, $url, $callback, array $settings = null) public static function match(array $requestMethods, string $url, $callback, array $settings = null)
{ {
$route = new RouteUrl($url, $callback); $route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods); $route->setRequestMethods($requestMethods);
@@ -287,7 +309,7 @@ class SimpleRouter
* @return RouteUrl|IRoute * @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function all($url, $callback, array $settings = null) public static function all(string $url, $callback, array $settings = null)
{ {
$route = new RouteUrl($url, $callback); $route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
@@ -310,7 +332,7 @@ class SimpleRouter
* @return RouteController|IRoute * @return RouteController|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function controller($url, $controller, array $settings = null) public static function controller(string $url, $controller, array $settings = null)
{ {
$route = new RouteController($url, $controller); $route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
@@ -333,7 +355,7 @@ class SimpleRouter
* @return RouteResource|IRoute * @return RouteResource|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function resource($url, $controller, array $settings = null) public static function resource(string $url, $controller, array $settings = null)
{ {
$route = new RouteResource($url, $controller); $route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
@@ -354,7 +376,7 @@ class SimpleRouter
* @return CallbackExceptionHandler $callbackHandler * @return CallbackExceptionHandler $callbackHandler
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function error(\Closure $callback) public static function error(\Closure $callback): CallbackExceptionHandler
{ {
$routes = static::router()->getRoutes(); $routes = static::router()->getRoutes();
@@ -389,7 +411,7 @@ class SimpleRouter
* @return string * @return string
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function getUrl($name = null, $parameters = null, $getParams = null) public static function getUrl(?string $name = null, $parameters = null, $getParams = null): string
{ {
return static::router()->getUrl($name, $parameters, $getParams); return static::router()->getUrl($name, $parameters, $getParams);
} }
@@ -400,7 +422,7 @@ class SimpleRouter
* @return \Pecee\Http\Request * @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function request() public static function request(): Request
{ {
return static::router()->getRequest(); return static::router()->getRequest();
} }
@@ -411,7 +433,7 @@ class SimpleRouter
* @return Response * @return Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function response() public static function response(): Response
{ {
if (static::$response === null) { if (static::$response === null) {
static::$response = new Response(static::request()); static::$response = new Response(static::request());
@@ -426,7 +448,7 @@ class SimpleRouter
* @return Router * @return Router
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function router() public static function router(): Router
{ {
if (static::$router === null) { if (static::$router === null) {
static::$router = new Router(); static::$router = new Router();
@@ -441,14 +463,14 @@ class SimpleRouter
* @param IRoute $route * @param IRoute $route
* @return IRoute * @return IRoute
*/ */
public static function addDefaultNamespace(IRoute $route) public static function addDefaultNamespace(IRoute $route): IRoute
{ {
if (static::$defaultNamespace !== null) { if (static::$defaultNamespace !== null) {
$callback = $route->getCallback(); $callback = $route->getCallback();
/* Only add default namespace on relative callbacks */ /* Only add default namespace on relative callbacks */
if ($callback === null || (is_string($callback) === true && $callback[0] !== '\\')) { if ($callback === null || (\is_string($callback) === true && $callback[0] !== '\\')) {
$namespace = static::$defaultNamespace; $namespace = static::$defaultNamespace;
@@ -468,9 +490,9 @@ class SimpleRouter
/** /**
* Get default namespace * Get default namespace
* @return string * @return string|null
*/ */
public static function getDefaultNamespace() public static function getDefaultNamespace(): ?string
{ {
return static::$defaultNamespace; return static::$defaultNamespace;
} }
-39
View File
@@ -1,39 +0,0 @@
<?php
class ResourceController implements \Pecee\Controllers\IResourceController
{
public function index()
{
echo 'index';
}
public function show($id)
{
echo 'show ' . $id;
}
public function store()
{
echo 'store';
}
public function create()
{
echo 'create';
}
public function edit($id)
{
echo 'edit ' . $id;
}
public function update($id)
{
echo 'update ' . $id;
}
public function destroy($id)
{
echo 'destroy ' . $id;
}
}
@@ -1,11 +1,11 @@
<?php <?php
require_once 'Exceptions/MiddlewareLoadedException.php'; require_once 'Exception/MiddlewareLoadedException.php';
use Pecee\Http\Request; use Pecee\Http\Request;
class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware
{ {
public function handle(Request $request) public function handle(Request $request) : void
{ {
throw new MiddlewareLoadedException('Middleware loaded!'); throw new MiddlewareLoadedException('Middleware loaded!');
} }
@@ -1,4 +1,5 @@
<?php <?php
class ExceptionHandlerException extends \Exception class ExceptionHandlerException extends \Exception
{ {
} }
@@ -2,7 +2,7 @@
class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
echo $error->getMessage(); echo $error->getMessage();
} }
@@ -2,13 +2,12 @@
class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
global $stack; global $stack;
$stack[] = static::class; $stack[] = static::class;
$request->setUrl('/'); $request->setUrl('/');
return $request;
} }
} }
@@ -2,13 +2,12 @@
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
global $stack; global $stack;
$stack[] = static::class; $stack[] = static::class;
$request->setUrl('/'); $request->setUrl('/');
return $request;
} }
} }
@@ -2,7 +2,7 @@
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
global $stack; global $stack;
$stack[] = static::class; $stack[] = static::class;
@@ -5,7 +5,7 @@ use Pecee\Http\Request;
class RewriteMiddleware implements IMiddleware { class RewriteMiddleware implements IMiddleware {
public function handle(Request $request) { public function handle(Request $request) : void {
$request->setRewriteCallback(function() { $request->setRewriteCallback(function() {
return 'ok'; return 'ok';
@@ -0,0 +1,46 @@
<?php
class ResourceController implements \Pecee\Controllers\IResourceController
{
public function index() : ?string
{
echo 'index';
return null;
}
public function show($id) : ?string
{
echo 'show ' . $id;
return null;
}
public function store() : ?string
{
echo 'store';
return null;
}
public function create() : ?string
{
echo 'create';
return null;
}
public function edit($id) : ?string
{
echo 'edit ' . $id;
return null;
}
public function update($id) : ?string
{
echo 'update ' . $id;
return null;
}
public function destroy($id) : ?string
{
echo 'destroy ' . $id;
return null;
}
}
@@ -2,9 +2,8 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
class GroupTest extends PHPUnit_Framework_TestCase class GroupTest extends \PHPUnit\Framework\TestCase
{ {
protected $result; protected $result;
@@ -37,6 +36,7 @@ class GroupTest extends PHPUnit_Framework_TestCase
TestRouter::debug('/api/v1/test', 'get'); TestRouter::debug('/api/v1/test', 'get');
$this->assertTrue(true);
} }
public function testMultipleRoutes() public function testMultipleRoutes()
@@ -61,6 +61,8 @@ class GroupTest extends PHPUnit_Framework_TestCase
}); });
TestRouter::debug('/my/match', 'get'); TestRouter::debug('/my/match', 'get');
$this->assertTrue(true);
} }
public function testUrls() public function testUrls()
@@ -3,13 +3,12 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php'; require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class MiddlewareTest extends PHPUnit_Framework_TestCase class MiddlewareTest extends \PHPUnit\Framework\TestCase
{ {
public function testMiddlewareFound() public function testMiddlewareFound()
{ {
$this->setExpectedException(MiddlewareLoadedException::class); $this->expectException(MiddlewareLoadedException::class);
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () { TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']); TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
@@ -29,6 +28,8 @@ class MiddlewareTest extends PHPUnit_Framework_TestCase
TestRouter::get('/my/test/url', 'DummyController@method1'); TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get'); TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
} }
} }
@@ -2,15 +2,14 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; require_once 'Dummy/Exception/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function testCallbackExceptionHandler() public function testCallbackExceptionHandler()
{ {
$this->setExpectedException(ExceptionHandlerException::class); $this->expectException(ExceptionHandlerException::class);
// Match normal route on alias // Match normal route on alias
TestRouter::get('/my-new-url', 'DummyController@method2'); TestRouter::get('/my-new-url', 'DummyController@method2');
@@ -22,6 +21,8 @@ class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
TestRouter::debugNoReset('/404-url', 'get'); TestRouter::debugNoReset('/404-url', 'get');
TestRouter::router()->reset(); TestRouter::router()->reset();
$this->assertTrue(true);
} }
} }
@@ -1,9 +1,8 @@
<?php <?php
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
class RouterControllerTest extends PHPUnit_Framework_TestCase class RouterControllerTest extends \PHPUnit\Framework\TestCase
{ {
public function testGet() public function testGet()
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php'; require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class RouterPartialGroupTest extends PHPUnit_Framework_TestCase class RouterPartialGroupTest extends \PHPUnit\Framework\TestCase
{ {
public function testParameters() public function testParameters()
@@ -1,9 +1,8 @@
<?php <?php
require_once 'Dummy/ResourceController.php'; require_once 'Dummy/ResourceController.php';
require_once 'Helpers/TestRouter.php';
class RouterResourceTest extends PHPUnit_Framework_TestCase class RouterResourceTest extends \PHPUnit\Framework\TestCase
{ {
public function testResourceStore() public function testResourceStore()
@@ -1,13 +1,12 @@
<?php <?php
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ResponseException.php'; require_once 'Dummy/Exception/ResponseException.php';
require_once 'Dummy/Handler/ExceptionHandlerFirst.php'; require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
require_once 'Dummy/Handler/ExceptionHandlerSecond.php'; require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php'; require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Helpers/TestRouter.php'; require_once 'Dummy/Middleware/RewriteMiddleware.php';
require_once 'Dummy/Middlewares/RewriteMiddleware.php';
class RouteRewriteTest extends PHPUnit_Framework_TestCase class RouteRewriteTest extends \PHPUnit\Framework\TestCase
{ {
/** /**
@@ -61,7 +60,7 @@ class RouteRewriteTest extends PHPUnit_Framework_TestCase
public function testRewriteExceptionMessage() public function testRewriteExceptionMessage()
{ {
$this->setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class); $this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) { TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
@@ -2,10 +2,9 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; require_once 'Dummy/Exception/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterRouteTest extends PHPUnit_Framework_TestCase class RouterRouteTest extends \PHPUnit\Framework\TestCase
{ {
protected $result = false; protected $result = false;
@@ -27,7 +26,7 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
public function testNotFound() public function testNotFound()
{ {
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException'); $this->expectException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1'); TestRouter::get('/non-existing-path', 'DummyController@method1');
TestRouter::debug('/test-param1-param2', 'post'); TestRouter::debug('/test-param1-param2', 'post');
} }
@@ -36,24 +35,32 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{ {
TestRouter::get('/my/test/url', 'DummyController@method1'); TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get'); TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
} }
public function testPost() public function testPost()
{ {
TestRouter::post('/my/test/url', 'DummyController@method1'); TestRouter::post('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'post'); TestRouter::debug('/my/test/url', 'post');
$this->assertTrue(true);
} }
public function testPut() public function testPut()
{ {
TestRouter::put('/my/test/url', 'DummyController@method1'); TestRouter::put('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'put'); TestRouter::debug('/my/test/url', 'put');
$this->assertTrue(true);
} }
public function testDelete() public function testDelete()
{ {
TestRouter::delete('/my/test/url', 'DummyController@method1'); TestRouter::delete('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'delete'); TestRouter::debug('/my/test/url', 'delete');
$this->assertTrue(true);
} }
public function testMethodNotAllowed() public function testMethodNotAllowed()
@@ -123,6 +130,8 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{ {
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']); TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
TestRouter::debug('/my/custom-path', 'get'); TestRouter::debug('/my/custom-path', 'get');
$this->assertTrue(true);
} }
public function testParameterDefaultValue() { public function testParameterDefaultValue() {
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php'; require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class RouterUrlTest extends PHPUnit_Framework_TestCase class RouterUrlTest extends \PHPUnit\Framework\TestCase
{ {
public function testIssue253() public function testIssue253()
+4
View File
@@ -0,0 +1,4 @@
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
require_once 'TestRouter.php';