diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 0000000..467daf9 --- /dev/null +++ b/.codeclimate.yml @@ -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/** diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 0000000..0608e7a --- /dev/null +++ b/.scrutinizer.yml @@ -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 + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..72c98f1 --- /dev/null +++ b/.travis.yml @@ -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 diff --git a/README.md b/README.md index f8c2c00..5a333b6 100644 --- a/README.md +++ b/README.md @@ -308,6 +308,8 @@ use Pecee\SimpleRouter\SimpleRouter as Router; * @param string|array|null $parameters * @param array|null $getParams * @return string + * @throws \InvalidArgumentException + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function url($name = null, $parameters = null, $getParams = null) { @@ -316,6 +318,7 @@ function url($name = null, $parameters = null, $getParams = null) /** * @return \Pecee\Http\Response + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function response() { @@ -324,6 +327,7 @@ function response() /** * @return \Pecee\Http\Request + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function request() { @@ -335,15 +339,16 @@ function request() * @param string|null $index Parameter index name * @param string|null $defaultValue Default return value * @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) { 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) @@ -358,12 +363,13 @@ function redirect($url, $code = null) /** * Get current csrf-token * @return string|null + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function csrf_token() { $baseVerifier = Router::router()->getCsrfVerifier(); if ($baseVerifier !== null) { - return $baseVerifier->getToken(); + return $baseVerifier->getTokenProvider()->getToken(); } return null; diff --git a/composer.json b/composer.json index 2fee7b4..9c88dd6 100644 --- a/composer.json +++ b/composer.json @@ -27,10 +27,11 @@ } ], "require": { - "php": ">=5.4.0" + "php": ">=7.1" }, "require-dev": { - "phpunit/phpunit": "4.7.7" + "phpunit/phpunit": "^6.0", + "mockery/mockery": "^1" }, "autoload": { "psr-4": { diff --git a/helpers.php b/helpers.php index 71ae2fb..2c4d86d 100644 --- a/helpers.php +++ b/helpers.php @@ -19,6 +19,7 @@ use Pecee\SimpleRouter\SimpleRouter as Router; * @param array|null $getParams * @return string * @throws \InvalidArgumentException + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function url($name = null, $parameters = null, $getParams = null) { @@ -27,6 +28,7 @@ function url($name = null, $parameters = null, $getParams = null) /** * @return \Pecee\Http\Response + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function response() { @@ -35,6 +37,7 @@ function response() /** * @return \Pecee\Http\Request + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function request() { @@ -46,15 +49,16 @@ function request() * @param string|null $index Parameter index name * @param string|null $defaultValue Default return value * @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) { 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) @@ -69,6 +73,7 @@ function redirect($url, $code = null) /** * Get current csrf-token * @return string|null + * @throws \Pecee\Http\Exceptions\MalformedUrlException */ function csrf_token() { diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..6e8f0c6 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,24 @@ + + + + + + tests/Pecee/SimpleRouter/ + + + + + src + + + diff --git a/src/Pecee/Controllers/IResourceController.php b/src/Pecee/Controllers/IResourceController.php index 502017f..5900467 100644 --- a/src/Pecee/Controllers/IResourceController.php +++ b/src/Pecee/Controllers/IResourceController.php @@ -1,47 +1,48 @@ callback, + \call_user_func($this->callback, $request, $error ); diff --git a/src/Pecee/Handlers/IExceptionHandler.php b/src/Pecee/Handlers/IExceptionHandler.php index d27237f..5cd21d8 100644 --- a/src/Pecee/Handlers/IExceptionHandler.php +++ b/src/Pecee/Handlers/IExceptionHandler.php @@ -1,4 +1,5 @@ index; } @@ -67,9 +67,9 @@ class InputFile implements IInputItem /** * Set input index * @param string $index - * @return static $this + * @return static */ - public function setIndex($index) + public function setIndex($index): IInputItem { $this->index = $index; @@ -79,7 +79,7 @@ class InputFile implements IInputItem /** * @return string */ - public function getSize() + public function getSize(): string { return $this->size; } @@ -87,9 +87,9 @@ class InputFile implements IInputItem /** * Set file size * @param int $size - * @return static $this + * @return static */ - public function setSize($size) + public function setSize($size): IInputItem { $this->size = $size; @@ -100,7 +100,7 @@ class InputFile implements IInputItem * Get mime-type of file * @return string */ - public function getMime() + public function getMime(): string { return $this->getType(); } @@ -108,7 +108,7 @@ class InputFile implements IInputItem /** * @return string */ - public function getType() + public function getType(): string { return $this->type; } @@ -116,9 +116,9 @@ class InputFile implements IInputItem /** * Set type * @param string $type - * @return static $this + * @return static */ - public function setType($type) + public function setType($type): IInputItem { $this->type = $type; @@ -130,7 +130,7 @@ class InputFile implements IInputItem * * @return string */ - public function getExtension() + public function getExtension(): string { return pathinfo($this->getFilename(), PATHINFO_EXTENSION); } @@ -140,7 +140,7 @@ class InputFile implements IInputItem * * @return string */ - public function getName() + public function getName(): string { return $this->name; } @@ -150,9 +150,9 @@ class InputFile implements IInputItem * Useful for adding validation etc. * * @param string $name - * @return static $this + * @return static */ - public function setName($name) + public function setName($name): IInputItem { $this->name = $name; @@ -163,9 +163,9 @@ class InputFile implements IInputItem * Set filename * * @param string $name - * @return static $this + * @return static */ - public function setFilename($name) + public function setFilename($name): IInputItem { $this->filename = $name; @@ -177,7 +177,7 @@ class InputFile implements IInputItem * * @return string mixed */ - public function getFilename() + public function getFilename(): string { return $this->filename; } @@ -188,7 +188,7 @@ class InputFile implements IInputItem * @param string $destination * @return bool */ - public function move($destination) + public function move($destination): bool { return move_uploaded_file($this->tmpName, $destination); } @@ -198,7 +198,7 @@ class InputFile implements IInputItem * * @return string */ - public function getContents() + public function getContents(): string { return file_get_contents($this->tmpName); } @@ -208,7 +208,7 @@ class InputFile implements IInputItem * * @return bool */ - public function hasError() + public function hasError(): bool { return ($this->getError() !== 0); } @@ -218,7 +218,7 @@ class InputFile implements IInputItem * * @return string */ - public function getError() + public function getError(): string { return $this->errors; } @@ -227,9 +227,9 @@ class InputFile implements IInputItem * Set error * * @param int $error - * @return static $this + * @return static */ - public function setError($error) + public function setError($error): IInputItem { $this->errors = (int)$error; @@ -239,7 +239,7 @@ class InputFile implements IInputItem /** * @return string */ - public function getTmpName() + public function getTmpName(): string { return $this->tmpName; } @@ -247,9 +247,9 @@ class InputFile implements IInputItem /** * Set file temp. name * @param string $name - * @return static $this + * @return static */ - public function setTmpName($name) + public function setTmpName($name): IInputItem { $this->tmpName = $name; @@ -261,7 +261,7 @@ class InputFile implements IInputItem return $this->getTmpName(); } - public function getValue() + public function getValue(): string { return $this->getFilename(); } @@ -270,14 +270,14 @@ class InputFile implements IInputItem * @param string $value * @return static */ - public function setValue($value) + public function setValue($value): IInputItem { $this->filename = $value; return $this; } - public function toArray() + public function toArray(): array { return [ 'tmp_name' => $this->tmpName, diff --git a/src/Pecee/Http/Input/Input.php b/src/Pecee/Http/Input/InputHandler.php similarity index 84% rename from src/Pecee/Http/Input/Input.php rename to src/Pecee/Http/Input/InputHandler.php index b40dfef..416a8e3 100644 --- a/src/Pecee/Http/Input/Input.php +++ b/src/Pecee/Http/Input/InputHandler.php @@ -5,7 +5,7 @@ namespace Pecee\Http\Input; use Pecee\Exceptions\InvalidArgumentException; use Pecee\Http\Request; -class Input +class InputHandler { /** * @var array @@ -42,26 +42,26 @@ class Input * Parse input values * */ - public function parseInputs() + public function parseInputs() : void { /* Parse get requests */ - if (count($_GET) !== 0) { + if (\count($_GET) !== 0) { $this->get = $this->handleGetPost($_GET); } /* Parse post requests */ $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); } - if (count($postVars) !== 0) { + if (\count($postVars) !== 0) { $this->post = $this->handleGetPost($postVars); } /* Parse get requests */ - if (count($_FILES) !== 0) { + if (\count($_FILES) !== 0) { $this->file = $this->parseFiles(); } } @@ -69,14 +69,14 @@ class Input /** * @return array */ - public function parseFiles() + public function parseFiles() : array { $list = []; foreach ((array)$_FILES as $key => $value) { // Handle array input - if (is_array($value['name']) === false) { + if (\is_array($value['name']) === false) { $values['index'] = $key; try { $list[$key] = InputFile::createFromArray($values + $value); @@ -101,7 +101,7 @@ class Input return $list; } - protected function rearrangeFiles(array $values, &$index, $original) + protected function rearrangeFiles(array $values, &$index, $original) : array { $originalIndex = $index[0]; @@ -111,7 +111,7 @@ class Input foreach ($values as $key => $value) { - if (is_array($original['name'][$key]) === false) { + if (\is_array($original['name'][$key]) === false) { try { @@ -152,14 +152,14 @@ class Input return $output; } - protected function handleGetPost(array $array) + protected function handleGetPost(array $array) : array { $list = []; foreach ($array as $key => $value) { // Handle array input - if (is_array($value) === false) { + if (\is_array($value) === false) { $list[$key] = new InputItem($key, $value); continue; } @@ -181,7 +181,7 @@ class Input */ 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) { - 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) { - 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) { - if ($methods !== null && is_string($methods) === true) { + if ($methods !== null && \is_string($methods) === true) { $methods = [$methods]; } $element = null; - if ($methods === null || in_array('get', $methods, false) === true) { + if ($methods === null || \in_array('get', $methods, true) === true) { $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); } - 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); } - return ($element !== null) ? $element : $defaultValue; + return $element ?? $defaultValue; } /** @@ -264,7 +264,7 @@ class Input * @param string $index * @return bool */ - public function exists($index) + public function exists($index) : bool { return ($this->getObject($index) !== null); } @@ -274,7 +274,7 @@ class Input * @param array|null $filter Only take items in filter * @return array */ - public function all(array $filter = null) + public function all(array $filter = null) : array { $output = $_GET + $_POST; diff --git a/src/Pecee/Http/Input/InputItem.php b/src/Pecee/Http/Input/InputItem.php index 7ca4b93..de00aa7 100644 --- a/src/Pecee/Http/Input/InputItem.php +++ b/src/Pecee/Http/Input/InputItem.php @@ -20,12 +20,12 @@ class InputItem implements IInputItem /** * @return string */ - public function getIndex() + public function getIndex(): string { return $this->index; } - public function setIndex($index) + public function setIndex($index): IInputItem { $this->index = $index; @@ -35,7 +35,7 @@ class InputItem implements IInputItem /** * @return string */ - public function getName() + public function getName(): string { return $this->name; } @@ -45,7 +45,7 @@ class InputItem implements IInputItem * @param string $name * @return static $this */ - public function setName($name) + public function setName($name): IInputItem { $this->name = $name; @@ -55,7 +55,7 @@ class InputItem implements IInputItem /** * @return string */ - public function getValue() + public function getValue(): string { return $this->value; } @@ -65,7 +65,7 @@ class InputItem implements IInputItem * @param string $value * @return static $this */ - public function setValue($value) + public function setValue($value): IInputItem { $this->value = $value; diff --git a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php index 67e57dd..613058a 100644 --- a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php +++ b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php @@ -9,8 +9,8 @@ use Pecee\Http\Security\ITokenProvider; class BaseCsrfVerifier implements IMiddleware { - const POST_KEY = 'csrf-token'; - const HEADER_KEY = 'X-CSRF-TOKEN'; + public const POST_KEY = 'csrf-token'; + public const HEADER_KEY = 'X-CSRF-TOKEN'; protected $except; protected $tokenProvider; @@ -29,21 +29,21 @@ class BaseCsrfVerifier implements IMiddleware * @param Request $request * @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; } - $max = count($this->except) - 1; + $max = \count($this->except) - 1; for ($i = $max; $i >= 0; $i--) { $url = $this->except[$i]; $url = rtrim($url, '/'); - if ($url[strlen($url) - 1] === '*') { + if ($url[\strlen($url) - 1] === '*') { $url = rtrim($url, '*'); - $skip = (stripos($request->getUrl()->getOriginalUrl(), $url) === 0); + $skip = $request->getUrl()->contains($url); } else { $skip = ($url === $request->getUrl()->getOriginalUrl()); } @@ -62,12 +62,12 @@ class BaseCsrfVerifier implements IMiddleware * @param Request $request * @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 ($token === null) { @@ -85,7 +85,7 @@ class BaseCsrfVerifier implements IMiddleware } - public function getTokenProvider() + public function getTokenProvider(): ITokenProvider { return $this->tokenProvider; } @@ -94,7 +94,7 @@ class BaseCsrfVerifier implements IMiddleware * Set token provider * @param ITokenProvider $provider */ - public function setTokenProvider(ITokenProvider $provider) + public function setTokenProvider(ITokenProvider $provider): void { $this->tokenProvider = $provider; } diff --git a/src/Pecee/Http/Middleware/IMiddleware.php b/src/Pecee/Http/Middleware/IMiddleware.php index 731144d..68daf8b 100644 --- a/src/Pecee/Http/Middleware/IMiddleware.php +++ b/src/Pecee/Http/Middleware/IMiddleware.php @@ -1,4 +1,5 @@ setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri'))); - $this->input = new Input($this); - $this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'))); + $this->inputHandler = new InputHandler($this); + $this->method = strtolower($this->inputHandler->get('_method', $this->getHeader('request-method'))); } - protected function parseHeaders() + protected function parseHeaders(): void { $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; } @@ -64,23 +64,23 @@ class Request /** * @return Url */ - public function getUrl() + public function getUrl(): Url { return $this->url; } /** - * @return string + * @return string|null */ - public function getHost() + public function getHost(): ?string { return $this->host; } /** - * @return string + * @return string|null */ - public function getMethod() + public function getMethod(): ?string { return $this->method; } @@ -89,7 +89,7 @@ class Request * Get http basic auth user * @return string|null */ - public function getUser() + public function getUser(): ?string { return $this->getHeader('php-auth-user'); } @@ -98,7 +98,7 @@ class Request * Get http basic auth password * @return string|null */ - public function getPassword() + public function getPassword(): ?string { return $this->getHeader('php-auth-pw'); } @@ -107,16 +107,16 @@ class Request * Get all headers * @return array */ - public function getHeaders() + public function getHeaders(): array { return $this->headers; } /** * Get id address - * @return string + * @return string|null */ - public function getIp() + public function getIp(): ?string { if ($this->getHeader('http-cf-connecting-ip') !== null) { return $this->getHeader('http-cf-connecting-ip'); @@ -133,27 +133,27 @@ class Request * Get remote address/ip * * @alias static::getIp - * @return string + * @return string|null */ - public function getRemoteAddr() + public function getRemoteAddr(): ?string { return $this->getIp(); } /** * Get referer - * @return string + * @return string|null */ - public function getReferer() + public function getReferer(): ?string { return $this->getHeader('http-referer'); } /** * Get user agent - * @return string + * @return string|null */ - public function getUserAgent() + public function getUserAgent(): ?string { return $this->getHeader('http-user-agent'); } @@ -166,18 +166,18 @@ class Request * * @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 - * @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 */ - 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 */ - public function isAjax() + public function isAjax(): bool { return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest'); } @@ -206,7 +206,7 @@ class Request * Get accept formats * @return array */ - public function getAcceptFormats() + public function getAcceptFormats(): array { return explode(',', $this->getHeader('http-accept')); } @@ -215,7 +215,7 @@ class Request * @param string|Url $url * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public function setUrl($url) + public function setUrl($url): void { $this->url = ($url instanceof Url) ? $url : new Url($url); } @@ -223,7 +223,7 @@ class Request /** * @param string $host */ - public function setHost($host) + public function setHost($host): void { $this->host = $host; } @@ -231,7 +231,7 @@ class Request /** * @param string $method */ - public function setMethod($method) + public function setMethod($method): void { $this->method = $method; } @@ -242,7 +242,7 @@ class Request * @param ILoadableRoute $route * @return static */ - public function setRewriteRoute(ILoadableRoute $route) + public function setRewriteRoute(ILoadableRoute $route): self { $this->hasRewrite = true; $this->rewriteRoute = SimpleRouter::addDefaultNamespace($route); @@ -255,7 +255,7 @@ class Request * * @return ILoadableRoute|null */ - public function getRewriteRoute() + public function getRewriteRoute(): ?ILoadableRoute { return $this->rewriteRoute; } @@ -263,9 +263,9 @@ class Request /** * Get rewrite url * - * @return string + * @return string|null */ - public function getRewriteUrl() + public function getRewriteUrl(): ?string { return $this->rewriteUrl; } @@ -276,7 +276,7 @@ class Request * @param string $rewriteUrl * @return static */ - public function setRewriteUrl($rewriteUrl) + public function setRewriteUrl(string $rewriteUrl): self { $this->hasRewrite = true; $this->rewriteUrl = rtrim($rewriteUrl, '/') . '/'; @@ -286,10 +286,10 @@ class Request /** * Set rewrite callback - * @param string $callback + * @param string|\Closure $callback * @return static */ - public function setRewriteCallback($callback) + public function setRewriteCallback($callback): self { $this->hasRewrite = true; @@ -300,37 +300,60 @@ class Request * Get loaded route * @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 */ - public function setLoadedRoute(ILoadableRoute $route) + public function setLoadedRoutes(array $routes): self { - $this->loadedRoute = $route; + $this->loadedRoutes = $routes; 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; } - public function setHasRewrite($value) + public function setHasRewrite($value): self { $this->hasRewrite = $value; return $this; } - public function isRewrite($url) + public function isRewrite($url): bool { return ($this->rewriteUrl === $url); } @@ -347,7 +370,7 @@ class Request public function __get($name) { - return isset($this->data[$name]) ? $this->data[$name] : null; + return $this->data[$name] ?? null; } } \ No newline at end of file diff --git a/src/Pecee/Http/Response.php b/src/Pecee/Http/Response.php index f9f46f1..9920132 100644 --- a/src/Pecee/Http/Response.php +++ b/src/Pecee/Http/Response.php @@ -19,7 +19,7 @@ class Response * @param int $code * @return static */ - public function httpCode($code) + public function httpCode($code): self { http_response_code($code); @@ -32,7 +32,7 @@ class Response * @param string $url * @param int $httpCode */ - public function redirect($url, $httpCode = null) + public function redirect($url, $httpCode = null): void { if ($httpCode !== null) { $this->httpCode($httpCode); @@ -42,7 +42,7 @@ class Response exit(0); } - public function refresh() + public function refresh(): void { $this->redirect($this->request->getUrl()->getOriginalUrl()); } @@ -52,7 +52,7 @@ class Response * @param string $name * @return static */ - public function auth($name = '') + public function auth($name = ''): self { $this->headers([ 'WWW-Authenticate: Basic realm="' . $name . '"', @@ -62,7 +62,7 @@ class Response return $this; } - public function cache($eTag, $lastModified = 2592000) + public function cache($eTag, $lastModified = 2592000): self { $this->headers([ @@ -77,8 +77,7 @@ class Response if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) { $this->header('HTTP/1.1 304 Not Modified'); - - exit(); + exit(0); } return $this; @@ -91,9 +90,9 @@ class Response * @param int $dept JSON debt. * @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.'); } @@ -107,7 +106,7 @@ class Response * @param string $value * @return static */ - public function header($value) + public function header($value): self { header($value); @@ -119,7 +118,7 @@ class Response * @param array $headers * @return static */ - public function headers(array $headers) + public function headers(array $headers): self { foreach ($headers as $header) { $this->header($header); diff --git a/src/Pecee/Http/Security/CookieTokenProvider.php b/src/Pecee/Http/Security/CookieTokenProvider.php index 209067f..a44f639 100644 --- a/src/Pecee/Http/Security/CookieTokenProvider.php +++ b/src/Pecee/Http/Security/CookieTokenProvider.php @@ -6,7 +6,7 @@ use Pecee\Http\Security\Exceptions\SecurityException; class CookieTokenProvider implements ITokenProvider { - const CSRF_KEY = 'CSRF-TOKEN'; + public const CSRF_KEY = 'CSRF-TOKEN'; protected $token; protected $cookieTimeoutMinutes = 120; @@ -30,24 +30,13 @@ class CookieTokenProvider implements ITokenProvider * @return string * @throws SecurityException */ - public function generateToken() + public function generateToken(): string { - if (function_exists('random_bytes') === true) { - try { - return bin2hex(random_bytes(32)); - } catch(\Exception $e) { - throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious()); - } + try { + return bin2hex(random_bytes(32)); + } catch (\Exception $e) { + 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; } /** @@ -56,7 +45,7 @@ class CookieTokenProvider implements ITokenProvider * @param string $token * @return bool */ - public function validate($token) + public function validate($token): bool { if ($token !== null && $this->getToken() !== null) { return hash_equals($token, $this->getToken()); @@ -71,7 +60,7 @@ class CookieTokenProvider implements ITokenProvider * * @param string $token */ - public function setToken($token) + public function setToken($token): void { $this->token = $token; setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/'); @@ -82,17 +71,17 @@ class CookieTokenProvider implements ITokenProvider * @param string|null $defaultValue * @return string|null */ - public function getToken($defaultValue = null) + public function getToken($defaultValue = null): ?string { $this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null; - return ($this->token !== null) ? $this->token : $defaultValue; + return $this->token ?? $defaultValue; } /** * Refresh existing token */ - public function refresh() + public function refresh(): void { if ($this->token !== null) { $this->setToken($this->token); @@ -103,7 +92,7 @@ class CookieTokenProvider implements ITokenProvider * Returns whether the csrf token has been defined * @return bool */ - public function hasToken() + public function hasToken(): bool { return isset($_COOKIE[static::CSRF_KEY]); } @@ -112,7 +101,7 @@ class CookieTokenProvider implements ITokenProvider * Get timeout for cookie in minutes * @return int */ - public function getCookieTimeoutMinutes() + public function getCookieTimeoutMinutes(): int { return $this->cookieTimeoutMinutes; } @@ -121,7 +110,7 @@ class CookieTokenProvider implements ITokenProvider * Set cookie timeout in minutes * @param $minutes */ - public function setCookieTimeoutMinutes($minutes) + public function setCookieTimeoutMinutes($minutes): void { $this->cookieTimeoutMinutes = $minutes; } diff --git a/src/Pecee/Http/Security/ITokenProvider.php b/src/Pecee/Http/Security/ITokenProvider.php index 6b1ee72..7b6307f 100644 --- a/src/Pecee/Http/Security/ITokenProvider.php +++ b/src/Pecee/Http/Security/ITokenProvider.php @@ -8,7 +8,7 @@ interface ITokenProvider /** * Refresh existing token */ - public function refresh(); + public function refresh(): void; /** * Validate valid CSRF token @@ -16,6 +16,14 @@ interface ITokenProvider * @param string $token * @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); } \ No newline at end of file diff --git a/src/Pecee/Http/Url.php b/src/Pecee/Http/Url.php index 6256c3e..e863a76 100644 --- a/src/Pecee/Http/Url.php +++ b/src/Pecee/Http/Url.php @@ -38,7 +38,7 @@ class Url * Check if url is using a secure protocol like https * @return bool */ - public function isSecure() + public function isSecure(): bool { return (strtolower($this->getScheme()) === 'https'); } @@ -47,7 +47,7 @@ class Url * Checks if url is relative * @return bool */ - public function isRelative() + public function isRelative(): bool { return ($this->getHost() === null); } @@ -56,7 +56,7 @@ class Url * Get url scheme * @return string|null */ - public function getScheme() + public function getScheme(): ?string { return $this->data['scheme']; } @@ -65,7 +65,7 @@ class Url * Get url host * @return string|null */ - public function getHost() + public function getHost(): ?string { return $this->data['host']; } @@ -74,7 +74,7 @@ class Url * Get url port * @return int|null */ - public function getPort() + public function getPort(): ?int { return ($this->data['port'] !== null) ? (int)$this->data['port'] : null; } @@ -83,7 +83,7 @@ class Url * Parse username from url * @return string|null */ - public function getUserName() + public function getUserName(): ?string { return $this->data['user']; } @@ -92,7 +92,7 @@ class Url * Parse password from url * @return string|null */ - public function getPassword() + public function getPassword(): ?string { return $this->data['pass']; } @@ -101,7 +101,7 @@ class Url * Get path from url * @return string */ - public function getPath() + public function getPath(): ?string { return $this->data['path']; } @@ -110,7 +110,7 @@ class Url * Get querystring from url * @return string|null */ - public function getQueryString() + public function getQueryString(): ?string { return $this->data['query']; } @@ -119,7 +119,7 @@ class Url * Get fragment from url (everything after #) * @return string|null */ - public function getFragment() + public function getFragment(): ?string { return $this->data['fragment']; } @@ -127,7 +127,7 @@ class Url /** * @return string */ - public function getOriginalUrl() + public function getOriginalUrl(): string { return $this->originalUrl; } @@ -139,7 +139,7 @@ class Url * @throws MalformedUrlException * @return array */ - public function parseUrl($url, $component = -1) + public function parseUrl($url, $component = -1): array { $encodedUrl = preg_replace_callback( '/[^:\/@?&=#]+/u', @@ -158,11 +158,16 @@ class Url return array_map('urldecode', $parts); } + public function contains($value): bool + { + return (stripos($this->getOriginalUrl(), $value) === false); + } + /** * Returns data array with information about the url * @return array */ - public function getData() + public function getData(): array { return $this->data; } diff --git a/src/Pecee/SimpleRouter/IRouterBootManager.php b/src/Pecee/SimpleRouter/IRouterBootManager.php index 08090ed..c3686ec 100644 --- a/src/Pecee/SimpleRouter/IRouterBootManager.php +++ b/src/Pecee/SimpleRouter/IRouterBootManager.php @@ -1,4 +1,5 @@ getMiddlewares() as $middleware) { - if (is_object($middleware) === false) { + if (\is_object($middleware) === false) { $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 */ @@ -59,7 +59,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * @param string $url * @return static */ - public function setUrl($url) + public function setUrl($url) : self { $this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/'; @@ -75,7 +75,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute return $this; } - public function getUrl() + public function getUrl() : string { return $this->url; } @@ -89,13 +89,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * @param string|null $name * @return string */ - public function findUrl($method = null, $parameters = null, $name = null) + public function findUrl($method = null, $parameters = null, $name = null) : string { $url = $this->getUrl(); $group = $this->getGroup(); - if ($group !== null && count($group->getDomains()) !== 0) { + if ($group !== null && \count($group->getDomains()) !== 0) { $url = '//' . $group->getDomains()[0] . $url; } @@ -114,7 +114,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute 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 = ''; } else { $p = (array)$parameters; @@ -144,7 +144,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * * @return string */ - public function getName() + public function getName() : string { return $this->name; } @@ -155,9 +155,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * @param string $name * @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 * @return static */ - public function setMatch($regex) + public function setMatch($regex) : ILoadableRoute { $this->regex = $regex; @@ -178,7 +178,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * * @return string */ - public function getMatch() + public function getMatch() : string { return $this->regex; } @@ -191,7 +191,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * @param string|array $name * @return static */ - public function name($name) + public function name($name) : ILoadableRoute { 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. * * @param string $name - * @return static $this + * @return static */ - public function setName($name) + public function setName($name) : ILoadableRoute { $this->name = $name; @@ -216,7 +216,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute * @param bool $merge * @return static */ - public function setSettings(array $values, $merge = false) + public function setSettings(array $values, $merge = false): IRoute { if (isset($values['as']) === true) { diff --git a/src/Pecee/SimpleRouter/Route/Route.php b/src/Pecee/SimpleRouter/Route/Route.php index 8ebd681..1cb70bc 100644 --- a/src/Pecee/SimpleRouter/Route/Route.php +++ b/src/Pecee/SimpleRouter/Route/Route.php @@ -8,15 +8,15 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; abstract class Route implements IRoute { - const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s'; - const PARAMETERS_DEFAULT_REGEX = '[\w]+'; + protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s'; + protected const PARAMETERS_DEFAULT_REGEX = '[\w]+'; - const REQUEST_TYPE_GET = 'get'; - const REQUEST_TYPE_POST = 'post'; - const REQUEST_TYPE_PUT = 'put'; - const REQUEST_TYPE_PATCH = 'patch'; - const REQUEST_TYPE_OPTIONS = 'options'; - const REQUEST_TYPE_DELETE = 'delete'; + public const REQUEST_TYPE_GET = 'get'; + public const REQUEST_TYPE_POST = 'post'; + public const REQUEST_TYPE_PUT = 'put'; + public const REQUEST_TYPE_PATCH = 'patch'; + public const REQUEST_TYPE_OPTIONS = 'options'; + public const REQUEST_TYPE_DELETE = 'delete'; public static $requestTypes = [ self::REQUEST_TYPE_GET, @@ -75,10 +75,10 @@ abstract class Route implements IRoute * Render route * * @param Request $request - * @return string|mixed + * @return string|null * @throws NotFoundHttpException */ - public function renderRoute(Request $request) + public function renderRoute(Request $request): ?string { $callback = $this->getCallback(); @@ -97,9 +97,9 @@ abstract class Route implements IRoute } /* Render callback function */ - if (is_callable($callback) === true) { + if (\is_callable($callback) === true) { /* 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 */ @@ -116,7 +116,7 @@ abstract class Route implements IRoute 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) @@ -138,7 +138,7 @@ abstract class Route implements IRoute $regex = ''; - if ($key < count($parameters[1])) { + if ($key < \count($parameters[1])) { $name = $parameters[1][$key]; @@ -151,7 +151,7 @@ abstract class Route implements IRoute if ($parameterRegex !== null) { $regex = $parameterRegex; } 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 */ - 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; } @@ -202,9 +202,9 @@ abstract class Route implements IRoute * Set allowed request methods * * @param array $methods - * @return static $this + * @return static */ - public function setRequestMethods(array $methods) + public function setRequestMethods(array $methods): IRoute { $this->requestMethods = $methods; @@ -216,7 +216,7 @@ abstract class Route implements IRoute * * @return array */ - public function getRequestMethods() + public function getRequestMethods(): array { return $this->requestMethods; } @@ -224,7 +224,7 @@ abstract class Route implements IRoute /** * @return IRoute|null */ - public function getParent() + public function getParent(): ?IRoute { return $this->parent; } @@ -234,7 +234,7 @@ abstract class Route implements IRoute * * @return IGroupRoute|null */ - public function getGroup() + public function getGroup(): ?IGroupRoute { return $this->group; } @@ -243,9 +243,9 @@ abstract class Route implements IRoute * Set group * * @param IGroupRoute $group - * @return static $this + * @return static */ - public function setGroup(IGroupRoute $group) + public function setGroup(IGroupRoute $group): IRoute { $this->group = $group; @@ -259,9 +259,9 @@ abstract class Route implements IRoute * Set parent route * * @param IRoute $parent - * @return static $this + * @return static */ - public function setParent(IRoute $parent) + public function setParent(IRoute $parent): IRoute { $this->parent = $parent; @@ -274,7 +274,7 @@ abstract class Route implements IRoute * @param string $callback * @return static */ - public function setCallback($callback) + public function setCallback($callback): IRoute { $this->callback = $callback; @@ -282,16 +282,16 @@ abstract class Route implements IRoute } /** - * @return string + * @return string|callable */ public function getCallback() { 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); return $tmp[1]; @@ -302,7 +302,7 @@ abstract class Route implements IRoute 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); return $tmp[0]; @@ -311,7 +311,7 @@ abstract class Route implements IRoute return null; } - public function setMethod($method) + public function setMethod($method): IRoute { $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 */ - public function toArray() + public function toArray(): array { $values = []; @@ -373,15 +373,15 @@ abstract class Route implements IRoute $values['namespace'] = $this->namespace; } - if (count($this->requestMethods) !== 0) { + if (\count($this->requestMethods) !== 0) { $values['method'] = $this->requestMethods; } - if (count($this->where) !== 0) { + if (\count($this->where) !== 0) { $values['where'] = $this->where; } - if (count($this->middlewares) !== 0) { + if (\count($this->middlewares) !== 0) { $values['middleware'] = $this->middlewares; } @@ -434,7 +434,7 @@ abstract class Route implements IRoute * * @return array */ - public function getWhere() + public function getWhere(): array { return $this->where; } @@ -470,12 +470,12 @@ abstract class Route implements IRoute * * @return array */ - public function getParameters() + public function getParameters(): array { /* Sort the parameters after the user-defined param order, if any */ $parameters = []; - if (count($this->originalParameters) !== 0) { + if (\count($this->originalParameters) !== 0) { $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 * 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; } @@ -523,7 +523,7 @@ abstract class Route implements IRoute * @param IMiddleware|string $middleware * @return static */ - public function addMiddleware($middleware) + public function addMiddleware($middleware): IRoute { $this->middlewares[] = $middleware; @@ -534,9 +534,9 @@ abstract class Route implements IRoute * Set middlewares array * * @param array $middlewares - * @return $this + * @return static */ - public function setMiddlewares(array $middlewares) + public function setMiddlewares(array $middlewares): IRoute { $this->middlewares = $middlewares; @@ -546,7 +546,7 @@ abstract class Route implements IRoute /** * @return array */ - public function getMiddlewares() + public function getMiddlewares(): array { return $this->middlewares; } @@ -570,7 +570,7 @@ abstract class Route implements IRoute * * @return string */ - public function getDefaultParameterRegex() + public function getDefaultParameterRegex(): string { return $this->defaultParameterRegex; } diff --git a/src/Pecee/SimpleRouter/Route/RouteController.php b/src/Pecee/SimpleRouter/Route/RouteController.php index 25cfe4f..898df28 100644 --- a/src/Pecee/SimpleRouter/Route/RouteController.php +++ b/src/Pecee/SimpleRouter/Route/RouteController.php @@ -24,7 +24,7 @@ class RouteController extends LoadableRoute implements IControllerRoute * @param string $name * @return bool */ - public function hasName($name) + public function hasName($name): bool { if ($this->name === null) { return false; @@ -35,7 +35,7 @@ class RouteController extends LoadableRoute implements IControllerRoute $method = substr($name, strrpos($name, '.') + 1); $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; } } @@ -49,7 +49,7 @@ class RouteController extends LoadableRoute implements IControllerRoute * @param string|null $name * @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) { $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) { if (stripos($method, $requestType) === 0) { - $method = (string)substr($method, strlen($requestType)); + $method = (string)substr($method, \strlen($requestType)); break; } } @@ -77,7 +77,7 @@ class RouteController extends LoadableRoute implements IControllerRoute $group = $this->getGroup(); - if ($group !== null && count($group->getDomains()) !== 0) { + if ($group !== null && \count($group->getDomains()) !== 0) { $url .= '//' . $group->getDomains()[0]; } @@ -86,9 +86,9 @@ class RouteController extends LoadableRoute implements IControllerRoute 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; } @@ -102,12 +102,12 @@ class RouteController extends LoadableRoute implements IControllerRoute $strippedUrl = trim(str_ireplace($this->url, '/', $url), '/'); $path = explode('/', $strippedUrl); - if (count($path) !== 0) { + if (\count($path) !== 0) { $method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0]; $this->method = $request->getMethod() . ucfirst($method); - $this->parameters = array_slice($path, 1); + $this->parameters = \array_slice($path, 1); // Set callback $this->setCallback($this->controller . '@' . $this->method); @@ -123,7 +123,7 @@ class RouteController extends LoadableRoute implements IControllerRoute * * @return string */ - public function getController() + public function getController(): string { return $this->controller; } @@ -134,7 +134,7 @@ class RouteController extends LoadableRoute implements IControllerRoute * @param string $controller * @return static */ - public function setController($controller) + public function setController($controller): IControllerRoute { $this->controller = $controller; @@ -144,9 +144,9 @@ class RouteController extends LoadableRoute implements IControllerRoute /** * Return active method * - * @return string + * @return string|null */ - public function getMethod() + public function getMethod(): ?string { return $this->method; } @@ -157,7 +157,7 @@ class RouteController extends LoadableRoute implements IControllerRoute * @param string $method * @return static */ - public function setMethod($method) + public function setMethod($method): IRoute { $this->method = $method; @@ -171,7 +171,7 @@ class RouteController extends LoadableRoute implements IControllerRoute * @param bool $merge * @return static */ - public function setSettings(array $values, $merge = false) + public function setSettings(array $values, $merge = false): IRoute { if (isset($values['names']) === true) { $this->names = $values['names']; diff --git a/src/Pecee/SimpleRouter/Route/RouteGroup.php b/src/Pecee/SimpleRouter/Route/RouteGroup.php index 4e3bde1..e2506d7 100644 --- a/src/Pecee/SimpleRouter/Route/RouteGroup.php +++ b/src/Pecee/SimpleRouter/Route/RouteGroup.php @@ -18,9 +18,9 @@ class RouteGroup extends Route implements IGroupRoute * @param Request $request * @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; } @@ -28,7 +28,7 @@ class RouteGroup extends Route implements IGroupRoute $parameters = $this->parseParameters($domain, $request->getHost(), '.*'); - if ($parameters !== null && count($parameters) !== 0) { + if ($parameters !== null && \count($parameters) !== 0) { $this->parameters = $parameters; @@ -46,9 +46,9 @@ class RouteGroup extends Route implements IGroupRoute * @param Request $request * @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; } @@ -64,9 +64,9 @@ class RouteGroup extends Route implements IGroupRoute * Add exception handler * * @param IExceptionHandler|string $handler - * @return static $this + * @return static */ - public function addExceptionHandler($handler) + public function addExceptionHandler($handler): IGroupRoute { $this->exceptionHandlers[] = $handler; @@ -77,9 +77,9 @@ class RouteGroup extends Route implements IGroupRoute * Set exception-handlers for group * * @param array $handlers - * @return static $this + * @return static */ - public function setExceptionHandlers(array $handlers) + public function setExceptionHandlers(array $handlers): IGroupRoute { $this->exceptionHandlers = $handlers; @@ -91,7 +91,7 @@ class RouteGroup extends Route implements IGroupRoute * * @return array */ - public function getExceptionHandlers() + public function getExceptionHandlers(): array { return $this->exceptionHandlers; } @@ -101,7 +101,7 @@ class RouteGroup extends Route implements IGroupRoute * * @return array */ - public function getDomains() + public function getDomains(): array { return $this->domains; } @@ -110,9 +110,9 @@ class RouteGroup extends Route implements IGroupRoute * Set allowed domains for group. * * @param array $domains - * @return $this + * @return static */ - public function setDomains(array $domains) + public function setDomains(array $domains): IGroupRoute { $this->domains = $domains; @@ -123,7 +123,7 @@ class RouteGroup extends Route implements IGroupRoute * @param string $prefix * @return static */ - public function setPrefix($prefix) + public function setPrefix($prefix): IGroupRoute { $this->prefix = '/' . trim($prefix, '/'); @@ -133,9 +133,9 @@ class RouteGroup extends Route implements IGroupRoute /** * Set prefix that child-routes will inherit. * - * @return string + * @return string|null */ - public function getPrefix() + public function getPrefix(): ?string { return $this->prefix; } @@ -147,7 +147,7 @@ class RouteGroup extends Route implements IGroupRoute * @param bool $merge * @return static */ - public function setSettings(array $values, $merge = false) + public function setSettings(array $values, $merge = false): IRoute { if (isset($values['prefix']) === true) { @@ -183,7 +183,7 @@ class RouteGroup extends Route implements IGroupRoute * * @return array */ - public function toArray() + public function toArray(): array { $values = []; @@ -195,7 +195,7 @@ class RouteGroup extends Route implements IGroupRoute $values['as'] = $this->name; } - if (count($this->parameters) !== 0) { + if (\count($this->parameters) !== 0) { $values['parameters'] = $this->parameters; } diff --git a/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php b/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php index 51b71e0..9656554 100644 --- a/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php +++ b/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php @@ -15,12 +15,12 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute * @param Request $request * @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; } - + if ($this->prefix !== null) { /* Parse parameters from current route */ $parameters = $this->parseParameters($this->prefix, $url); diff --git a/src/Pecee/SimpleRouter/Route/RouteResource.php b/src/Pecee/SimpleRouter/Route/RouteResource.php index 108e51a..7d454b4 100644 --- a/src/Pecee/SimpleRouter/Route/RouteResource.php +++ b/src/Pecee/SimpleRouter/Route/RouteResource.php @@ -42,7 +42,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute * @param string $name * @return bool */ - public function hasName($name) + public function hasName($name): bool { if ($this->name === null) { return false; @@ -60,7 +60,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute 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); if ($url !== false) { @@ -77,9 +77,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute 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; } @@ -114,7 +114,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute } // 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']); } @@ -145,7 +145,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute /** * @return string */ - public function getController() + public function getController(): string { return $this->controller; } @@ -154,14 +154,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute * @param string $controller * @return static */ - public function setController($controller) + public function setController($controller): IControllerRoute { $this->controller = $controller; return $this; } - public function setName($name) + public function setName($name): ILoadableRoute { $this->name = $name; @@ -194,9 +194,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute /** * Get method names * - * @return array $this + * @return array */ - public function getMethodNames() + public function getMethodNames(): array { return $this->methodNames; } @@ -208,7 +208,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute * @param bool $merge * @return static */ - public function setSettings(array $values, $merge = false) + public function setSettings(array $values, $merge = false): IRoute { if (isset($values['names']) === true) { $this->names = $values['names']; diff --git a/src/Pecee/SimpleRouter/Route/RouteUrl.php b/src/Pecee/SimpleRouter/Route/RouteUrl.php index 19eb137..cdfcb60 100644 --- a/src/Pecee/SimpleRouter/Route/RouteUrl.php +++ b/src/Pecee/SimpleRouter/Route/RouteUrl.php @@ -12,9 +12,9 @@ class RouteUrl extends LoadableRoute $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; } diff --git a/src/Pecee/SimpleRouter/Router.php b/src/Pecee/SimpleRouter/Router.php index a34e350..c4d8f22 100644 --- a/src/Pecee/SimpleRouter/Router.php +++ b/src/Pecee/SimpleRouter/Router.php @@ -78,7 +78,7 @@ class Router /** * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public function reset() + public function reset() : void { $this->processingRoute = false; $this->request = new Request(); @@ -94,7 +94,7 @@ class Router * @param IRoute $route * @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 @@ -115,13 +115,13 @@ class Router * @param IRoute $route * @throws NotFoundHttpException */ - protected function renderAndProcess(IRoute $route) { + protected function renderAndProcess(IRoute $route) : void { $this->processingRoute = true; $route->renderRoute($this->request); $this->processingRoute = false; - if (count($this->routeStack) !== 0) { + if (\count($this->routeStack) !== 0) { /* Pop and grab the routes added when executing group callback earlier */ $stack = $this->routeStack; @@ -139,7 +139,7 @@ class Router * @param IGroupRoute|null $group * @throws NotFoundHttpException */ - protected function processRoutes(array $routes, IGroupRoute $group = null) + protected function processRoutes(array $routes, IGroupRoute $group = null) : void { // Loop through each route-request $exceptionHandlers = []; @@ -149,7 +149,7 @@ class Router return; } - $url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath(); + $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath(); /* @var $route IRoute */ foreach ($routes as $route) { @@ -165,7 +165,7 @@ class Router if ($route->matchRoute($url, $this->request) === true) { /* Add exception handlers */ - if (count($route->getExceptionHandlers()) !== 0) { + if (\count($route->getExceptionHandlers()) !== 0) { /** @noinspection AdditionOperationOnArraysInspection */ $exceptionHandlers += $route->getExceptionHandlers(); } @@ -199,7 +199,7 @@ class Router * @throws NotFoundHttpException * @return void */ - public function loadRoutes() + public function loadRoutes() : void { /* Initialize boot-managers */ /* @var $manager IRouterBootManager */ @@ -215,11 +215,11 @@ class Router * Routes the request * * @param bool $rewrite - * @return string|mixed + * @return string|null * @throws HttpException * @throws \Exception */ - public function routeRequest($rewrite = false) + public function routeRequest($rewrite = false) : ?string { $routeNotAllowed = false; @@ -237,7 +237,7 @@ class Router $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 */ foreach ($this->processedRoutes as $key => $route) { @@ -246,7 +246,7 @@ class Router if ($route->matchRoute($url, $this->request) === true) { /* 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; continue; } @@ -262,7 +262,7 @@ class Router /* Render route */ $routeNotAllowed = false; - $this->request->setLoadedRoute($route); + $this->request->addLoadedRoute($route); $output = $route->renderRoute($this->request); @@ -287,7 +287,7 @@ class Router $this->handleException(new HttpException($message, 403)); } - if ($this->request->getLoadedRoute() === null) { + if (\count($this->request->getLoadedRoutes()) === 0) { $rewriteUrl = $this->request->getRewriteUrl(); @@ -303,7 +303,7 @@ class Router return null; } - protected function hasRewrite($url) + protected function hasRewrite($url) : bool { /* If the request has changed */ @@ -332,14 +332,14 @@ class Router * @param \Exception $e * @throws HttpException * @throws \Exception - * @return string + * @return string|null */ - protected function handleException(\Exception $e) + protected function handleException(\Exception $e) : ?string { /* @var $handler IExceptionHandler */ foreach ($this->exceptionHandlers as $key => $handler) { - if (is_object($handler) === false) { + if (\is_object($handler) === false) { $handler = new $handler(); } @@ -366,9 +366,9 @@ class Router 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) { $getParams = array_filter($getParams, function ($item) { @@ -388,13 +388,13 @@ class Router * @param string $name * @return ILoadableRoute|null */ - public function findRoute($name) + public function findRoute($name) : ?ILoadableRoute { /* @var $route ILoadableRoute */ foreach ($this->processedRoutes as $route) { /* 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; } @@ -404,8 +404,8 @@ class Router } /* Using @ is most definitely a controller@method or alias@method */ - if (is_string($name) === true && strpos($name, '@') !== false) { - list($controller, $method) = array_map('strtolower', explode('@', $name)); + if (\is_string($name) === true && strpos($name, '@') !== false) { + [$controller, $method] = array_map('strtolower', explode('@', $name)); if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) { return $route; @@ -413,7 +413,7 @@ class Router } /* 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 */ if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) { @@ -448,9 +448,9 @@ class Router * @throws InvalidArgumentException * @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'); } @@ -485,8 +485,8 @@ class Router } /* Using @ is most definitely a controller@method or alias@method */ - if (is_string($name) === true && strpos($name, '@') !== false) { - list($controller, $method) = explode('@', $name); + if (\is_string($name) === true && strpos($name, '@') !== false) { + [$controller, $method] = explode('@', $name); /* Loop through all the routes to see if we can find a match */ @@ -516,7 +516,7 @@ class Router * Get bootmanagers * @return array */ - public function getBootManagers() + public function getBootManagers() : array { return $this->bootManagers; } @@ -525,7 +525,7 @@ class Router * Set bootmanagers * @param array $bootManagers */ - public function setBootManagers(array $bootManagers) + public function setBootManagers(array $bootManagers) : void { $this->bootManagers = $bootManagers; } @@ -534,7 +534,7 @@ class Router * Add bootmanager * @param IRouterBootManager $bootManager */ - public function addBootManager(IRouterBootManager $bootManager) + public function addBootManager(IRouterBootManager $bootManager) : void { $this->bootManagers[] = $bootManager; } @@ -544,7 +544,7 @@ class Router * * @return array */ - public function getProcessedRoutes() + public function getProcessedRoutes() : array { return $this->processedRoutes; } @@ -552,7 +552,7 @@ class Router /** * @return array */ - public function getRoutes() + public function getRoutes() : array { return $this->routes; } @@ -561,9 +561,9 @@ class Router * Set routes * * @param array $routes - * @return static $this + * @return static */ - public function setRoutes(array $routes) + public function setRoutes(array $routes) : self { $this->routes = $routes; @@ -575,7 +575,7 @@ class Router * * @return Request */ - public function getRequest() + public function getRequest() : Request { return $this->request; } @@ -584,7 +584,7 @@ class Router * Get csrf verifier class * @return BaseCsrfVerifier */ - public function getCsrfVerifier() + public function getCsrfVerifier() : BaseCsrfVerifier { return $this->csrfVerifier; } diff --git a/src/Pecee/SimpleRouter/SimpleRouter.php b/src/Pecee/SimpleRouter/SimpleRouter.php index 81b6014..8f64e70 100644 --- a/src/Pecee/SimpleRouter/SimpleRouter.php +++ b/src/Pecee/SimpleRouter/SimpleRouter.php @@ -13,12 +13,15 @@ namespace Pecee\SimpleRouter; use Pecee\Exceptions\InvalidArgumentException; use Pecee\Handlers\CallbackExceptionHandler; use Pecee\Http\Middleware\BaseCsrfVerifier; +use Pecee\Http\Request; use Pecee\Http\Response; use Pecee\SimpleRouter\Exceptions\HttpException; +use Pecee\SimpleRouter\Route\IGroupRoute; +use Pecee\SimpleRouter\Route\IPartialGroupRoute; use Pecee\SimpleRouter\Route\IRoute; -use Pecee\SimpleRouter\Route\RoutePartialGroup; use Pecee\SimpleRouter\Route\RouteController; use Pecee\SimpleRouter\Route\RouteGroup; +use Pecee\SimpleRouter\Route\RoutePartialGroup; use Pecee\SimpleRouter\Route\RouteResource; use Pecee\SimpleRouter\Route\RouteUrl; @@ -26,7 +29,7 @@ class SimpleRouter { /** * Default namespace added to all routes - * @var string + * @var string|null */ protected static $defaultNamespace; @@ -47,17 +50,36 @@ class SimpleRouter * @throws HttpException * @throws \Exception */ - public static function start() + public static function start(): void { 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. * * @param string $defaultNamespace */ - public static function setDefaultNamespace($defaultNamespace) + public static function setDefaultNamespace(string $defaultNamespace): void { static::$defaultNamespace = $defaultNamespace; } @@ -68,7 +90,7 @@ class SimpleRouter * @param BaseCsrfVerifier $baseCsrfVerifier * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) + public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier): void { static::router()->setCsrfVerifier($baseCsrfVerifier); } @@ -80,7 +102,7 @@ class SimpleRouter * @param IRouterBootManager $bootManager * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public static function addBootManager(IRouterBootManager $bootManager) + public static function addBootManager(IRouterBootManager $bootManager): void { static::router()->addBootManager($bootManager); } @@ -95,7 +117,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -109,7 +131,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -123,7 +145,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -137,7 +159,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -151,7 +173,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -165,7 +187,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -179,9 +201,9 @@ class SimpleRouter * @throws \Pecee\Http\Exceptions\MalformedUrlException * @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'); } @@ -205,9 +227,9 @@ class SimpleRouter * @throws \Pecee\Http\Exceptions\MalformedUrlException * @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'); } @@ -232,7 +254,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -248,7 +270,7 @@ class SimpleRouter * @return RouteUrl * @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); } @@ -263,7 +285,7 @@ class SimpleRouter * @return RouteUrl|IRoute * @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->setRequestMethods($requestMethods); @@ -287,7 +309,7 @@ class SimpleRouter * @return RouteUrl|IRoute * @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 = static::addDefaultNamespace($route); @@ -310,7 +332,7 @@ class SimpleRouter * @return RouteController|IRoute * @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 = static::addDefaultNamespace($route); @@ -333,7 +355,7 @@ class SimpleRouter * @return RouteResource|IRoute * @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 = static::addDefaultNamespace($route); @@ -354,7 +376,7 @@ class SimpleRouter * @return CallbackExceptionHandler $callbackHandler * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public static function error(\Closure $callback) + public static function error(\Closure $callback): CallbackExceptionHandler { $routes = static::router()->getRoutes(); @@ -389,7 +411,7 @@ class SimpleRouter * @return string * @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); } @@ -400,7 +422,7 @@ class SimpleRouter * @return \Pecee\Http\Request * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public static function request() + public static function request(): Request { return static::router()->getRequest(); } @@ -411,7 +433,7 @@ class SimpleRouter * @return Response * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public static function response() + public static function response(): Response { if (static::$response === null) { static::$response = new Response(static::request()); @@ -426,7 +448,7 @@ class SimpleRouter * @return Router * @throws \Pecee\Http\Exceptions\MalformedUrlException */ - public static function router() + public static function router(): Router { if (static::$router === null) { static::$router = new Router(); @@ -441,14 +463,14 @@ class SimpleRouter * @param IRoute $route * @return IRoute */ - public static function addDefaultNamespace(IRoute $route) + public static function addDefaultNamespace(IRoute $route): IRoute { if (static::$defaultNamespace !== null) { $callback = $route->getCallback(); /* 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; @@ -468,9 +490,9 @@ class SimpleRouter /** * Get default namespace - * @return string + * @return string|null */ - public static function getDefaultNamespace() + public static function getDefaultNamespace(): ?string { return static::$defaultNamespace; } diff --git a/test/Dummy/ResourceController.php b/test/Dummy/ResourceController.php deleted file mode 100644 index 8536563..0000000 --- a/test/Dummy/ResourceController.php +++ /dev/null @@ -1,39 +0,0 @@ -getMessage(); } diff --git a/test/Dummy/Handler/ExceptionHandlerFirst.php b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerFirst.php similarity index 87% rename from test/Dummy/Handler/ExceptionHandlerFirst.php rename to tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerFirst.php index 8a5f807..561ebde 100644 --- a/test/Dummy/Handler/ExceptionHandlerFirst.php +++ b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerFirst.php @@ -2,13 +2,12 @@ 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; $stack[] = static::class; $request->setUrl('/'); - return $request; } } \ No newline at end of file diff --git a/test/Dummy/Handler/ExceptionHandlerSecond.php b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerSecond.php similarity index 86% rename from test/Dummy/Handler/ExceptionHandlerSecond.php rename to tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerSecond.php index d629a03..2360047 100644 --- a/test/Dummy/Handler/ExceptionHandlerSecond.php +++ b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerSecond.php @@ -2,13 +2,12 @@ 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; $stack[] = static::class; $request->setUrl('/'); - return $request; } } \ No newline at end of file diff --git a/test/Dummy/Handler/ExceptionHandlerThird.php b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerThird.php similarity index 92% rename from test/Dummy/Handler/ExceptionHandlerThird.php rename to tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerThird.php index 15923ec..d295157 100644 --- a/test/Dummy/Handler/ExceptionHandlerThird.php +++ b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerThird.php @@ -2,7 +2,7 @@ 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; $stack[] = static::class; diff --git a/test/Dummy/Middlewares/RewriteMiddleware.php b/tests/Pecee/SimpleRouter/Dummy/Middleware/RewriteMiddleware.php similarity index 79% rename from test/Dummy/Middlewares/RewriteMiddleware.php rename to tests/Pecee/SimpleRouter/Dummy/Middleware/RewriteMiddleware.php index 7bd1fef..f107bbd 100644 --- a/test/Dummy/Middlewares/RewriteMiddleware.php +++ b/tests/Pecee/SimpleRouter/Dummy/Middleware/RewriteMiddleware.php @@ -5,7 +5,7 @@ use Pecee\Http\Request; class RewriteMiddleware implements IMiddleware { - public function handle(Request $request) { + public function handle(Request $request) : void { $request->setRewriteCallback(function() { return 'ok'; diff --git a/tests/Pecee/SimpleRouter/Dummy/ResourceController.php b/tests/Pecee/SimpleRouter/Dummy/ResourceController.php new file mode 100644 index 0000000..0a70e6f --- /dev/null +++ b/tests/Pecee/SimpleRouter/Dummy/ResourceController.php @@ -0,0 +1,46 @@ +assertTrue(true); } public function testMultipleRoutes() @@ -61,6 +61,8 @@ class GroupTest extends PHPUnit_Framework_TestCase }); TestRouter::debug('/my/match', 'get'); + + $this->assertTrue(true); } public function testUrls() diff --git a/test/MiddlewareTest.php b/tests/Pecee/SimpleRouter/MiddlewareTest.php similarity index 83% rename from test/MiddlewareTest.php rename to tests/Pecee/SimpleRouter/MiddlewareTest.php index d3c4dba..0183c59 100644 --- a/test/MiddlewareTest.php +++ b/tests/Pecee/SimpleRouter/MiddlewareTest.php @@ -3,13 +3,12 @@ require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyController.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() { - $this->setExpectedException(MiddlewareLoadedException::class); + $this->expectException(MiddlewareLoadedException::class); TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () { 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::debug('/my/test/url', 'get'); + + $this->assertTrue(true); } } \ No newline at end of file diff --git a/test/RouterCallbackExceptionHandlerTest.php b/tests/Pecee/SimpleRouter/RouterCallbackExceptionHandlerTest.php similarity index 69% rename from test/RouterCallbackExceptionHandlerTest.php rename to tests/Pecee/SimpleRouter/RouterCallbackExceptionHandlerTest.php index de21d2a..bf6514f 100644 --- a/test/RouterCallbackExceptionHandlerTest.php +++ b/tests/Pecee/SimpleRouter/RouterCallbackExceptionHandlerTest.php @@ -2,15 +2,14 @@ require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyController.php'; -require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; -require_once 'Helpers/TestRouter.php'; +require_once 'Dummy/Exception/ExceptionHandlerException.php'; -class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase +class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase { public function testCallbackExceptionHandler() { - $this->setExpectedException(ExceptionHandlerException::class); + $this->expectException(ExceptionHandlerException::class); // Match normal route on alias TestRouter::get('/my-new-url', 'DummyController@method2'); @@ -22,6 +21,8 @@ class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase TestRouter::debugNoReset('/404-url', 'get'); TestRouter::router()->reset(); + + $this->assertTrue(true); } } \ No newline at end of file diff --git a/test/RouterControllerTest.php b/tests/Pecee/SimpleRouter/RouterControllerTest.php similarity index 89% rename from test/RouterControllerTest.php rename to tests/Pecee/SimpleRouter/RouterControllerTest.php index 3c39bc2..fff6566 100644 --- a/test/RouterControllerTest.php +++ b/tests/Pecee/SimpleRouter/RouterControllerTest.php @@ -1,9 +1,8 @@ setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class); + $this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class); TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) { diff --git a/test/RouterRouteTest.php b/tests/Pecee/SimpleRouter/RouterRouteTest.php similarity index 91% rename from test/RouterRouteTest.php rename to tests/Pecee/SimpleRouter/RouterRouteTest.php index c503b28..63d69f9 100644 --- a/test/RouterRouteTest.php +++ b/tests/Pecee/SimpleRouter/RouterRouteTest.php @@ -2,10 +2,9 @@ require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyController.php'; -require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; -require_once 'Helpers/TestRouter.php'; +require_once 'Dummy/Exception/ExceptionHandlerException.php'; -class RouterRouteTest extends PHPUnit_Framework_TestCase +class RouterRouteTest extends \PHPUnit\Framework\TestCase { protected $result = false; @@ -27,7 +26,7 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase public function testNotFound() { - $this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException'); + $this->expectException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException'); TestRouter::get('/non-existing-path', 'DummyController@method1'); TestRouter::debug('/test-param1-param2', 'post'); } @@ -36,24 +35,32 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase { TestRouter::get('/my/test/url', 'DummyController@method1'); TestRouter::debug('/my/test/url', 'get'); + + $this->assertTrue(true); } public function testPost() { TestRouter::post('/my/test/url', 'DummyController@method1'); TestRouter::debug('/my/test/url', 'post'); + + $this->assertTrue(true); } public function testPut() { TestRouter::put('/my/test/url', 'DummyController@method1'); TestRouter::debug('/my/test/url', 'put'); + + $this->assertTrue(true); } public function testDelete() { TestRouter::delete('/my/test/url', 'DummyController@method1'); TestRouter::debug('/my/test/url', 'delete'); + + $this->assertTrue(true); } 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::debug('/my/custom-path', 'get'); + + $this->assertTrue(true); } public function testParameterDefaultValue() { diff --git a/test/RouterUrlTest.php b/tests/Pecee/SimpleRouter/RouterUrlTest.php similarity index 98% rename from test/RouterUrlTest.php rename to tests/Pecee/SimpleRouter/RouterUrlTest.php index f7d986d..5c6d0e7 100644 --- a/test/RouterUrlTest.php +++ b/tests/Pecee/SimpleRouter/RouterUrlTest.php @@ -3,9 +3,8 @@ require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyController.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() diff --git a/test/Helpers/TestRouter.php b/tests/TestRouter.php similarity index 100% rename from test/Helpers/TestRouter.php rename to tests/TestRouter.php diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..22f8cd2 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,4 @@ +