Compare commits

..

17 Commits

Author SHA1 Message Date
Simon Sessingø 7c0a20115e Merge pull request #336 from skipperbent/v3-development
Version 3.4.9.0
2017-12-09 23:58:33 +01:00
Simon Sessingø 877e0aa937 Merge pull request #334 from skipperbent/v3-development
Version 3.4.8.0
2017-12-06 19:06:09 +01:00
Simon Sessingø 3e7767d978 Merge pull request #330 from skipperbent/v3-development
V3 development
2017-12-02 20:30:27 +01:00
Simon Sessingø 5ef9349b18 Merge pull request #327 from skipperbent/v3-development
Version 3.4.6.4
2017-11-27 02:05:17 +01:00
Simon Sessingø 264f0a7b0f Merge pull request #325 from skipperbent/v3-development
Version 3.4.6.3
2017-11-27 00:01:30 +01:00
Simon Sessingø 5197ae2990 Merge pull request #323 from skipperbent/v3-development
Version 3.4.6.2
2017-11-26 23:44:06 +01:00
Simon Sessingø 9c701aabee Merge pull request #321 from skipperbent/v3-development
Fixed url parsing issues
2017-11-26 18:45:54 +01:00
Simon Sessingø 2b0821a557 Merge pull request #320 from skipperbent/v3-development
Fixed typo
2017-11-26 18:29:36 +01:00
Simon Sessingø afc81d7005 Merge pull request #318 from skipperbent/v3-development
Version 3.4.6.0
2017-11-26 18:08:24 +01:00
Simon Sessingø 496d3e7182 Merge pull request #315 from skipperbent/v3-development
Version 3.4.5.5
2017-11-25 01:34:53 +01:00
Simon Sessingø 1fd13ed2aa Merge pull request #311 from skipperbent/v3-development
V3 development
2017-11-10 13:02:49 +01:00
Simon Sessingø 9d5c4a2ed1 Merge pull request #308 from skipperbent/v3-development
3.4.5.4
2017-11-10 08:24:55 +01:00
Simon Sessingø b8634bcf79 Merge pull request #307 from skipperbent/revert-306-revert-305-v3-development
Revert "Revert "V3 development""
2017-11-08 04:11:50 +01:00
Simon Sessingø 6ad22a3816 Revert "Revert "V3 development"" 2017-11-08 04:11:40 +01:00
Simon Sessingø ed41cd55af Merge pull request #306 from skipperbent/revert-305-v3-development
Revert "V3 development"
2017-11-08 04:09:55 +01:00
Simon Sessingø ebeca952cf Revert "V3 development" 2017-11-08 04:09:41 +01:00
Simon Sessingø 0672e85fd7 Merge pull request #305 from skipperbent/v3-development
V3 development
2017-11-08 04:09:31 +01:00
30 changed files with 393 additions and 577 deletions
+159 -53
View File
@@ -1,18 +1,45 @@
# Simple PHP router
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expandability in mind.
**Please note that this documentation is currently work-in-progress. Feel free to contribute.**
**Note: this documentation is currently work-in-progress. Feel free to contribute.**
### Notes
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
### Feedback and development
If you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.
###### Issues guidelines
- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue.
For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.
- We love to hear out any ideas or feedback to the library.
[Create a new issue here](https://github.com/skipperbent/simple-php-router/issues/new)
###### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
- When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
---
## Table of Contents
- [Getting started](#getting-started)
- [Notes](#notes-1)
- [Requirements](#requirements)
- [Feedback and development](#feedback-and-development)
- [Issues guidelines](#issues-guidelines)
- [Contribution development guidelines](#contribution-development-guidelines)
- [Notes](#notes-1)
- [Features](#features)
- [Installation](#installation)
- [Setting up Apache](#setting-up-apache)
@@ -20,6 +47,7 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a
- [Setting up IIS](#setting-up-iis)
- [Configuration](#configuration)
- [Helper functions](#helper-functions)
- [Routes](#routes)
- [Basic routing](#basic-routing)
- [Available methods](#available-methods)
@@ -71,7 +99,8 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a
- [Advanced](#advanced)
- [Url rewriting](#url-rewriting)
- [Changing current route](#changing-current-route)
- [Rewrite using callback](#rewrite-using-callback)
- [Rewrite using url](#rewrite-using-url)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Adding routes manually](#adding-routes-manually)
- [Parameters](#parameters)
@@ -90,9 +119,11 @@ Add the latest version of Simple PHP Router running this command.
composer require pecee/simple-router
```
## Notes
## Requirements
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
- PHP 5.5 or greater
## Notes
We've included a simple demo project for the router which can be found in the `demo-project` folder. This project should give you a basic understanding of how to setup and use simple-php-router project.
@@ -112,36 +143,6 @@ You can find the demo-project here: [https://github.com/skipperbent/simple-route
- How to get ExceptionHandlers, Middlewares and Controllers working.
- How to setup your webservers.
## Requirements
- PHP 5.5 or greater
### Feedback and development
If you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.
###### Issues guidelines
- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue.
For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.
- We love to hear out any ideas or feedback to the library.
[Create a new issue here](https://github.com/skipperbent/simple-php-router/issues/new)
###### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
- When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
## Features
- Basic routing (`GET`, `POST`, `PUT`, `PATCH`, `UPDATE`, `DELETE`) with support for custom multiple verbs.
@@ -597,9 +598,9 @@ SimpleRouter::group(['namespace' => 'Admin'], function () {
});
```
### Subdomain-routing
### Sub domain-routing
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route urls, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the `domain` key on the group attribute array:
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the `domain` key on the group attribute array:
```php
SimpleRouter::group(['domain' => '{account}.myapp.com'], function () {
@@ -611,7 +612,7 @@ SimpleRouter::group(['domain' => '{account}.myapp.com'], function () {
### Route prefixes
The `prefix` group attribute may be used to prefix each route in the group with a given url. For example, you may want to prefix all route urls within the group with `admin`:
The `prefix` group attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with `admin`:
```php
SimpleRouter::group(['prefix' => '/admin'], function () {
@@ -843,7 +844,7 @@ class CustomMiddleware implements Middleware {
// If authentication failed, redirect request to user-login page.
if($request->user === null) {
$request->setRewriteUrl(url('user.login'));
return;
return $request;
}
}
@@ -893,7 +894,7 @@ class CustomExceptionHandler implements IExceptionHandler
/* You can use the exception handler to format errors depending on the request and type. */
if (stripos($request->getUrl()->getPath(), '/api') !== false) {
if (stripos($request->getUri()->getPath(), '/api') !== false) {
response()->json([
'error' => $error->getMessage(),
@@ -908,7 +909,7 @@ class CustomExceptionHandler implements IExceptionHandler
// Render custom 404-page
$request->setRewriteCallback('Demo\Controllers\PageController@notFound');
return;
return $request;
}
@@ -1134,22 +1135,126 @@ $siteId = input('site_id', 2, ['post', 'get']);
# Advanced
## Url rewriting
### Changing current route
Sometimes it can be useful to manipulate the route about to be loaded.
simple-php-router allows you to easily manipulate and change the routes which are about to be rendered.
simple-php-router allows you to easily change the route about to be executed.
All information about the current route is stored in the `\Pecee\SimpleRouter\Router` instance's `loadedRoute` property.
For easy access you can use the shortcut helper function `request()` instead of calling the class directly `\Pecee\SimpleRouter\SimpleRouter::router()`.
For easy access you can use the shortcut method `\Pecee\SimpleRouter\SimpleRouter::router()`.
```php
request()->setRewriteCallback('Example\MyCustomClass@hello');
use Pecee\SimpleRouter;
$request = SimpleRouter::request();
$request->setRewriteCallback('Example\MyCustomClass@hello');
// -- or you can rewrite by url --
request()->setRewriteUrl('/my-rewrite-url');
$request->setRewriteUrl('/my-rewrite-url');
```
**Note:** It's only possible to change the route BEFORE the route has initially been rendered. You can use the `Request` object to manipulate the route which are about to be loaded.
### Rewrite using callback
This method is most efficient, as it will render the route immediately.
This method is useful for rendering 404-pages etc.
You can also change the callback by modifying the `$route` parameter. This is perfect if you just want to display a view quickly - or change the callback depending
on some criteria's for the request.
The callback below will fire immediately after the `Middleware` or `ExceptionHandler` has been loaded, as they are loaded before the route is rendered.
If you wish to change the callback from outside, please have this in mind.
The example below will render `DefaultController@notFound` regardless of the url.
**NOTE: Use this method if you want to load another controller. No additional middlewares or rules will be loaded.**
##### Middleware example
```php
namespace Demo\Middlewares;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class CustomMiddleware implements IMiddleware {
public function handle(Request $request) {
$request->setRewriteCallback('Demo\Controllers\DefaultController@notFound');
return $request;
}
}
```
##### Exception handler example
```php
namespace Demo\Handlers;
use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
class CustomExceptionHandler implements IExceptionHandler
{
public function handleError(Request $request, \Exception $error)
{
/* The router will throw the NotFoundHttpException on 404 */
if($error instanceof NotFoundHttpException) {
/*
* Render your own custom 404-view, rewrite the request to another route,
* or simply return the $request object to ignore the error and continue on rendering the route.
*
* The code below will make the router render our page.notfound route.
*/
$request->setRewriteCallback('Demo\Controllers\DefaultController@notFound');
return $request;
}
throw $error;
}
}
```
### Rewrite using url
The example below will cause the router to reload the request and reinitialize all the routes. This method is slower, but will ensure that all middlewares and rules for the route is loaded.
This method is useful if you want to redirect a url to another-url which is dependent on a middleware. You can also add a custom rule by calling `$request->setRewriteRoute($route)` if
you want to customize request-methods or use another route-type like `RouteController` etc.
We are using the `url()` helper function to get the uri to another route added in the `routes.php` file.
**NOTE: Use this method if you want to fully load another route using it's settings (request method, middlewares etc).**
##### Middleware example
The example below will redirect the request to the `home`-route.
```php
namespace Demo\Middlewares;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class CustomMiddleware implements IMiddleware {
public function handle(Request $request) {
$request->setRewriteUrl(url('home'));
return $request;
}
}
```
### Bootmanager: loading routes dynamically
@@ -1173,10 +1278,11 @@ class CustomRouterRules implement IRouterBootManager {
foreach($rewriteRules as $url => $rule) {
// If the current url matches the rewrite url, we use our custom route
// If the current uri matches the url, we use our custom route
if($request->getUrl()->getPath() === $url) {
if($request->getUri()->getPath() === $url) {
$request->setRewriteUrl($rule);
return $request;
}
}
+1 -6
View File
@@ -9,12 +9,7 @@
"simple-php-router",
"laravel",
"pecee",
"php",
"framework",
"url-handling",
"input-handler",
"routing-engine",
"request-handler"
"php"
],
"license": "MIT",
"support": {
-1
View File
@@ -18,7 +18,6 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param string|array|null $parameters
* @param array|null $getParams
* @return string
* @throws \InvalidArgumentException
*/
function url($name = null, $parameters = null, $getParams = null)
{
@@ -1,6 +0,0 @@
<?php
namespace Pecee\Exceptions;
class InvalidArgumentException extends \InvalidArgumentException {
}
@@ -1,8 +0,0 @@
<?php
namespace Pecee\Http\Exceptions;
class MalformedUrlException extends \Exception
{
}
-3
View File
@@ -1,5 +1,4 @@
<?php
namespace Pecee\Http\Input;
interface IInputItem
@@ -15,8 +14,6 @@ interface IInputItem
public function getValue();
public function setValue($value);
public function __toString();
}
+19 -41
View File
@@ -2,7 +2,6 @@
namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Request;
class Input
@@ -27,10 +26,6 @@ class Input
*/
protected $request;
/**
* Input constructor.
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
@@ -38,10 +33,6 @@ class Input
$this->parseInputs();
}
/**
* Parse input values
*
*/
public function parseInputs()
{
/* Parse get requests */
@@ -66,9 +57,6 @@ class Input
}
}
/**
* @return array
*/
public function parseFiles()
{
$list = [];
@@ -78,11 +66,7 @@ class Input
// Handle array input
if (is_array($value['name']) === false) {
$values['index'] = $key;
try {
$list[$key] = InputFile::createFromArray($values + $value);
} catch(InvalidArgumentException $e ){
}
$list[$key] = InputFile::createFromArray($values + $value);
continue;
}
@@ -113,28 +97,22 @@ class Input
if (is_array($original['name'][$key]) === false) {
try {
$file = InputFile::createFromArray([
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
'name' => $original['name'][$key],
'error' => $original['error'][$key],
'tmp_name' => $original['tmp_name'][$key],
'type' => $original['type'][$key],
'size' => $original['size'][$key],
]);
$file = InputFile::createFromArray([
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
'name' => $original['name'][$key],
'error' => $original['error'][$key],
'tmp_name' => $original['tmp_name'][$key],
'type' => $original['type'][$key],
'size' => $original['size'][$key],
]);
if (isset($output[$key]) === true) {
$output[$key][] = $file;
continue;
}
$output[$key] = $file;
if (isset($output[$key]) === true) {
$output[$key][] = $file;
continue;
} catch(InvalidArgumentException $e) {
}
$output[$key] = $file;
continue;
}
$index[] = $key;
@@ -276,21 +254,21 @@ class Input
*/
public function all(array $filter = null)
{
$output = $_GET + $_POST;
$output = $_POST;
if ($this->request->getMethod() === 'post') {
$contents = file_get_contents('php://input');
if (strpos(trim($contents), '{') === 0) {
$post = json_decode($contents, true);
if ($post !== false) {
$output += $post;
$output = json_decode($contents, true);
if ($output === false) {
$output = [];
}
}
}
return ($filter !== null) ? array_intersect_key($output, array_flip($filter)) : $output;
return ($filter !== null) ? array_intersect_key($output, array_flip($filter)) : array_merge($_GET, $output);
}
}
+6 -21
View File
@@ -2,8 +2,6 @@
namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException;
class InputFile implements IInputItem
{
public $index;
@@ -11,15 +9,13 @@ class InputFile implements IInputItem
public $filename;
public $size;
public $type;
public $errors;
public $error;
public $tmpName;
public function __construct($index)
{
$this->index = $index;
$this->errors = 0;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', strtolower($this->index)));
}
@@ -28,13 +24,13 @@ class InputFile implements IInputItem
* Create from array
*
* @param array $values
* @throws InvalidArgumentException
* @throws \InvalidArgumentException
* @return static
*/
public static function createFromArray(array $values)
{
if (isset($values['index']) === false) {
throw new InvalidArgumentException('Index key is required');
throw new \InvalidArgumentException('Index key is required');
}
/* Easy way of ensuring that all indexes-are set and not filling the screen with isset() */
@@ -220,7 +216,7 @@ class InputFile implements IInputItem
*/
public function getError()
{
return $this->errors;
return $this->error;
}
/**
@@ -231,7 +227,7 @@ class InputFile implements IInputItem
*/
public function setError($error)
{
$this->errors = (int)$error;
$this->error = (int)$error;
return $this;
}
@@ -266,17 +262,6 @@ class InputFile implements IInputItem
return $this->getFilename();
}
/**
* @param string $value
* @return static
*/
public function setValue($value)
{
$this->filename = $value;
return $this;
}
public function toArray()
{
return [
@@ -284,7 +269,7 @@ class InputFile implements IInputItem
'type' => $this->type,
'size' => $this->size,
'name' => $this->name,
'error' => $this->errors,
'error' => $this->error,
'filename' => $this->filename,
];
}
-1
View File
@@ -1,5 +1,4 @@
<?php
namespace Pecee\Http\Input;
class InputItem implements IInputItem
@@ -15,10 +15,6 @@ class BaseCsrfVerifier implements IMiddleware
protected $except;
protected $tokenProvider;
/**
* BaseCsrfVerifier constructor.
* @throws \Pecee\Http\Security\Exceptions\SecurityException
*/
public function __construct()
{
$this->tokenProvider = new CookieTokenProvider();
@@ -43,9 +39,9 @@ class BaseCsrfVerifier implements IMiddleware
$url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUrl()->getOriginalUrl(), $url) === 0);
$skip = (stripos($request->getUri()->getPath(), $url) === 0);
} else {
$skip = ($url === $request->getUrl()->getOriginalUrl());
$skip = ($url === $request->getUri()->getPath());
}
if ($skip === true) {
+11 -49
View File
@@ -12,12 +12,10 @@ class Request
private $data = [];
protected $headers;
protected $host;
protected $url;
protected $uri;
protected $method;
protected $input;
protected $hasRewrite = false;
/**
* @var ILoadableRoute|null
*/
@@ -29,20 +27,16 @@ class Request
*/
protected $loadedRoute;
/**
* Request constructor.
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function __construct()
{
$this->parseHeaders();
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
$this->setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri')));
$this->setUri(new Uri($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->method = strtolower($this->input->get('_method', $this->getHeader('request-method'), 'post'));
}
protected function parseHeaders()
@@ -62,11 +56,11 @@ class Request
}
/**
* @return Url
* @return Uri
*/
public function getUrl()
public function getUri()
{
return $this->url;
return $this->uri;
}
/**
@@ -192,16 +186,6 @@ class Request
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
}
/**
* Returns true if the request is made through Ajax
*
* @return bool
*/
public function isAjax()
{
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
}
/**
* Get accept formats
* @return array
@@ -212,12 +196,11 @@ class Request
}
/**
* @param string|Url $url
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @param Uri $uri
*/
public function setUrl($url)
public function setUri(Uri $uri)
{
$this->url = ($url instanceof Url) ? $url : new Url($url);
$this->uri = $uri;
}
/**
@@ -244,7 +227,6 @@ class Request
*/
public function setRewriteRoute(ILoadableRoute $route)
{
$this->hasRewrite = true;
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
return $this;
@@ -278,8 +260,7 @@ class Request
*/
public function setRewriteUrl($rewriteUrl)
{
$this->hasRewrite = true;
$this->rewriteUrl = rtrim($rewriteUrl, '/') . '/';
$this->rewriteUrl = $rewriteUrl;
return $this;
}
@@ -291,9 +272,7 @@ class Request
*/
public function setRewriteCallback($callback)
{
$this->hasRewrite = true;
return $this->setRewriteRoute(new RouteUrl($this->getUrl()->getPath(), $callback));
return $this->setRewriteRoute(new RouteUrl($this->uri, $callback));
}
/**
@@ -318,23 +297,6 @@ class Request
return $this;
}
public function hasRewrite()
{
return $this->hasRewrite;
}
public function setHasRewrite($value)
{
$this->hasRewrite = $value;
return $this;
}
public function isRewrite($url)
{
return ($this->rewriteUrl === $url);
}
public function __isset($name)
{
return array_key_exists($name, $this->data);
+4 -6
View File
@@ -2,8 +2,6 @@
namespace Pecee\Http;
use Pecee\Exceptions\InvalidArgumentException;
class Response
{
protected $request;
@@ -39,12 +37,12 @@ class Response
}
$this->header('location: ' . $url);
exit(0);
die();
}
public function refresh()
{
$this->redirect($this->request->getUrl()->getOriginalUrl());
$this->redirect($this->request->getUri()->getPath());
}
/**
@@ -89,12 +87,12 @@ class Response
* @param array|\JsonSerializable $value
* @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param int $dept JSON debt.
* @throws InvalidArgumentException
* @throws \InvalidArgumentException
*/
public function json($value, $options = null, $dept = 512)
{
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.');
}
$this->header('Content-Type: application/json; charset=utf-8');
@@ -2,8 +2,6 @@
namespace Pecee\Http\Security;
use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider
{
const CSRF_KEY = 'CSRF-TOKEN';
@@ -11,10 +9,6 @@ class CookieTokenProvider implements ITokenProvider
protected $token;
protected $cookieTimeoutMinutes = 120;
/**
* CookieTokenProvider constructor.
* @throws SecurityException
*/
public function __construct()
{
$this->token = $this->getToken();
@@ -27,24 +21,20 @@ class CookieTokenProvider implements ITokenProvider
/**
* Generate random identifier for CSRF token
*
* @throws \RuntimeException|\Exception
* @return string
* @throws SecurityException
*/
public function generateToken()
{
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());
}
return bin2hex(random_bytes(32));
}
$isSourceStrong = false;
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
if ($isSourceStrong === false || $random === false) {
throw new SecurityException('IV generation failed');
throw new \RuntimeException('IV generation failed');
}
return $random;
@@ -1,6 +0,0 @@
<?php
namespace Pecee\Http\Security\Exceptions;
class SecurityException extends \Exception {
}
@@ -2,9 +2,7 @@
namespace Pecee\Http;
use Pecee\Http\Exceptions\MalformedUrlException;
class Url
class Uri
{
private $originalUrl;
private $data = [
@@ -18,11 +16,6 @@ class Url
'fragment' => null,
];
/**
* Url constructor.
* @param string $url
* @throws MalformedUrlException
*/
public function __construct($url)
{
$this->originalUrl = $url;
@@ -136,7 +129,7 @@ class Url
* UTF-8 aware parse_url() replacement.
* @param string $url
* @param int $component
* @throws MalformedUrlException
* @throws \InvalidArgumentException
* @return array
*/
public function parseUrl($url, $component = -1)
@@ -152,7 +145,7 @@ class Url
$parts = parse_url($encodedUrl, $component);
if ($parts === false) {
throw new MalformedUrlException('Malformed URL: ' . $url);
throw new \InvalidArgumentException('Malformed URL: ' . $url);
}
return array_map('urldecode', $parts);
+17 -5
View File
@@ -28,7 +28,15 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*/
public function loadMiddleware(Request $request)
{
foreach ($this->getMiddlewares() as $middleware) {
$max = count($this->getMiddlewares());
if ($max === 0) {
return;
}
for ($i = 0; $i < $max; $i++) {
$middleware = $this->getMiddlewares()[$i];
if (is_object($middleware) === false) {
$middleware = $this->loadClass($middleware);
@@ -50,7 +58,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return null;
}
return ((bool)preg_match($this->regex, $request->getHost() . $url) !== false);
return (preg_match($this->regex, $request->getHost() . $url) > 0);
}
/**
@@ -67,7 +75,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
if ((bool)preg_match_all('/' . $regex . '/u', $this->url, $matches) !== false) {
if (preg_match_all('/' . $regex . '/u', $this->url, $matches) > 0) {
$this->parameters = array_fill_keys($matches[1], null);
}
}
@@ -111,8 +119,11 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
/* Replace any {parameter} in the url with the correct value */
$params = $this->getParameters();
$max = count($params) - 1;
$keys = array_keys($params);
foreach (array_keys($params) as $param) {
for ($i = $max; $i >= 0; $i--) {
$param = $keys[$i];
if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
$value = '';
@@ -134,7 +145,8 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
}
}
$url = '/' . ltrim($url, '/') . implode('/', $unknownParams);
$url = '/' . ltrim($url, '/');
$url .= implode('/', $unknownParams);
return rtrim($url, '/') . '/';
}
+29 -28
View File
@@ -33,7 +33,7 @@ abstract class Route implements IRoute
*
* @var bool
*/
protected $filterEmptyParams = true;
protected $filterEmptyParams = false;
/**
* Default regular expression used for parsing parameters.
@@ -86,20 +86,12 @@ abstract class Route implements IRoute
return null;
}
$parameters = $this->getParameters();
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) {
return ($var !== null);
});
}
/* Render callback function */
if (is_callable($callback) === true) {
/* When the callback is a function */
return call_user_func_array($callback, $parameters);
return call_user_func_array($callback, $this->getParameters());
}
/* When the callback is a class + method */
@@ -116,6 +108,16 @@ abstract class Route implements IRoute
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
}
$parameters = $this->getParameters();
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) {
return ($var !== null);
});
}
return call_user_func_array([$class, $method], $parameters);
}
@@ -128,9 +130,7 @@ abstract class Route implements IRoute
// Ensures that hostnames/domains will work with parameters
$url = '/' . ltrim($url, '/');
if ((bool)preg_match_all('/' . $regex . '/u', $route, $parameters) === false) {
$urlRegex = preg_quote($route, '/');
} else {
if (preg_match_all('/' . $regex . '/u', $route, $parameters) > 0) {
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', $route);
@@ -156,6 +156,7 @@ abstract class Route implements IRoute
}
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
}
$urlParts[$key] = preg_quote($t, '/') . $regex;
@@ -163,23 +164,26 @@ abstract class Route implements IRoute
$urlRegex = implode('', $urlParts);
} else {
$urlRegex = preg_quote($route, '/');
}
if ((bool)preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === false) {
return null;
}
if (preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) > 0) {
$values = [];
$values = [];
if (isset($parameters[1]) === true) {
if (isset($parameters[1]) === true) {
/* Only take matched parameters with name */
foreach ((array)$parameters[1] as $name) {
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
/* Only take matched parameters with name */
foreach ((array)$parameters[1] as $name) {
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
}
}
return $values;
}
return $values;
return null;
}
/**
@@ -249,9 +253,6 @@ abstract class Route implements IRoute
{
$this->group = $group;
/* Add/merge parent settings with child */
$this->setSettings($group->toArray(), true);
return $this;
}
@@ -544,7 +545,7 @@ abstract class Route implements IRoute
}
/**
* @return array
* @return string|array
*/
public function getMiddlewares()
{
@@ -88,10 +88,6 @@ class RouteController extends LoadableRoute implements IControllerRoute
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
@@ -48,10 +48,6 @@ class RouteGroup extends Route implements IGroupRoute
*/
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
return false;
@@ -17,10 +17,6 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
*/
public function matchRoute($url, Request $request)
{
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);
@@ -79,10 +79,6 @@ class RouteResource extends LoadableRoute implements IControllerRoute
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
@@ -14,10 +14,6 @@ class RouteUrl extends LoadableRoute
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
+116 -120
View File
@@ -2,7 +2,6 @@
namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
@@ -17,6 +16,12 @@ use Pecee\SimpleRouter\Route\IRoute;
class Router
{
/**
* The instance of this class
* @var static
*/
protected static $instance;
/**
* Current request
* @var Request
@@ -66,18 +71,11 @@ class Router
*/
protected $exceptionHandlers;
/**
* Router constructor.
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function __construct()
{
$this->reset();
}
/**
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function reset()
{
$this->processingRoute = false;
@@ -97,64 +95,52 @@ class Router
public function addRoute(IRoute $route)
{
/*
* If a route is currently being processed, that means that the route being added are rendered from the parent
* routes callback, so we add them to the stack instead.
* If a route is currently being processed, that means that the
* route being added are rendered from the parent routes callback,
* so we add them to the stack instead.
*/
if ($this->processingRoute === true) {
$this->routeStack[] = $route;
return $route;
} else {
$this->routes[] = $route;
}
$this->routes[] = $route;
return $route;
}
/**
* Render and process any new routes added.
*
* @param IRoute $route
* @throws NotFoundHttpException
*/
protected function renderAndProcess(IRoute $route) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
if (count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
$this->routeStack = [];
/* Route any routes added to the stack */
$this->processRoutes($stack, $route);
}
}
/**
* Process added routes.
*
* @param array $routes
* @param IGroupRoute|null $group
* @param IRoute|null $parent
* @throws NotFoundHttpException
*/
protected function processRoutes(array $routes, IGroupRoute $group = null)
protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null)
{
// Loop through each route-request
$max = count($routes) - 1;
$exceptionHandlers = [];
// Stop processing routes if no valid route is found.
if($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
return;
}
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath();
for ($i = $max; $i >= 0; $i--) {
/* @var $route IRoute */
foreach ($routes as $route) {
$route = $routes[$i];
if ($parent !== null) {
/* Add the parent route */
$route->setParent($parent);
/* Add/merge parent settings with child */
$route->setSettings($parent->toArray(), true);
}
if ($group !== null) {
/* Add the parent group */
$route->setGroup($group);
}
@@ -162,6 +148,8 @@ class Router
/* @var $route IGroupRoute */
if ($route instanceof IGroupRoute) {
$group = $route;
if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */
@@ -171,24 +159,36 @@ class Router
}
/* Only render partial group if it matches */
if ($route instanceof IPartialGroupRoute === true) {
$this->renderAndProcess($route);
if ($route instanceof IPartialGroupRoute) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
}
}
if ($route instanceof IPartialGroupRoute === false) {
$this->renderAndProcess($route);
if (($route instanceof IPartialGroupRoute) === false) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
}
continue;
}
if ($route instanceof ILoadableRoute === true) {
if ($route instanceof ILoadableRoute) {
/* Add the route to the map, so we can find the active one when all routes has been loaded */
$this->processedRoutes[] = $route;
}
if (count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
$this->routeStack = [];
/* Route any routes added to the stack */
$this->processRoutes($stack, $route, $group);
}
}
$this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
@@ -202,9 +202,15 @@ class Router
public function loadRoutes()
{
/* Initialize boot-managers */
/* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) {
$manager->boot($this->request);
if (count($this->bootManagers) !== 0) {
$max = count($this->bootManagers) - 1;
/* @var $manager IRouterBootManager */
for ($i = $max; $i >= 0; $i--) {
$manager = $this->bootManagers[$i];
$manager->boot($this->request);
}
}
/* Loop through each route-request */
@@ -233,14 +239,16 @@ class Router
/* Verify csrf token for request */
$this->csrfVerifier->handle($this->request);
}
} else {
$this->request->setHasRewrite(false);
}
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath();
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
$max = count($this->processedRoutes) - 1;
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $key => $route) {
for ($i = $max; $i >= 0; $i--) {
$route = $this->processedRoutes[$i];
/* If the route matches */
if ($route->matchRoute($url, $this->request) === true) {
@@ -253,28 +261,29 @@ class Router
$route->loadMiddleware($this->request);
if ($this->hasRewrite($url) === true) {
unset($this->processedRoutes[$key]);
$rewriteRoute = $this->request->getRewriteRoute();
if ($rewriteRoute !== null) {
$rewriteRoute->loadMiddleware($this->request);
return $rewriteRoute->renderRoute($this->request);
}
/* If the request has changed */
$rewriteUrl = $this->request->getRewriteUrl();
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
unset($this->processedRoutes[$i]);
$this->processedRoutes = array_values($this->processedRoutes);
return $this->routeRequest(true);
}
/* Render route */
$routeNotAllowed = false;
$this->request->setLoadedRoute($route);
$output = $route->renderRoute($this->request);
if ($output !== null) {
return $output;
}
if ($this->hasRewrite($url) === true) {
unset($this->processedRoutes[$key]);
return $this->routeRequest(true);
}
return $route->renderRoute($this->request);
}
}
@@ -283,7 +292,7 @@ class Router
}
if ($routeNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod());
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUri()->getPath(), $this->request->getMethod());
$this->handleException(new HttpException($message, 403));
}
@@ -292,9 +301,9 @@ class Router
$rewriteUrl = $this->request->getRewriteUrl();
if ($rewriteUrl !== null) {
$message = sprintf('Route not found: "%s" (rewrite from: "%s")', $rewriteUrl, $this->request->getUrl()->getPath());
$message = sprintf('Route not found: "%s" (rewrite from: "%s")', $rewriteUrl, $this->request->getUri()->getPath());
} else {
$message = sprintf('Route not found: "%s"', $this->request->getUrl()->getPath());
$message = sprintf('Route not found: "%s"', $this->request->getUri()->getPath());
}
$this->handleException(new NotFoundHttpException($message, 404));
@@ -303,31 +312,6 @@ class Router
return null;
}
protected function hasRewrite($url)
{
/* If the request has changed */
if ($this->request->hasRewrite() === true) {
if ($this->request->getRewriteRoute() !== null) {
/* Render rewrite-route */
$this->processedRoutes[] = $this->request->getRewriteRoute();
return true;
}
if ($this->request->isRewrite($url) === false) {
/* Render rewrite-url */
$this->processedRoutes = array_values($this->processedRoutes);
return true;
}
}
return false;
}
/**
* @param \Exception $e
* @throws HttpException
@@ -336,6 +320,8 @@ class Router
*/
protected function handleException(\Exception $e)
{
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
/* @var $handler IExceptionHandler */
foreach ($this->exceptionHandlers as $key => $handler) {
@@ -349,13 +335,25 @@ class Router
try {
$handler->handleError($this->request, $e);
if ($handler->handleError($this->request, $e) !== null) {
if ($this->request->hasRewrite() === true) {
unset($this->exceptionHandlers[$key]);
$this->exceptionHandlers = array_values($this->exceptionHandlers);
$rewriteRoute = $this->request->getRewriteRoute();
return $this->routeRequest(true);
if ($rewriteRoute !== null) {
$rewriteRoute->loadMiddleware($this->request);
return $rewriteRoute->renderRoute($this->request);
}
$rewriteUrl = $this->request->getRewriteUrl();
/* If the request has changed */
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
unset($this->exceptionHandlers[$key]);
$this->exceptionHandlers = array_values($this->exceptionHandlers);
return $this->routeRequest(true);
}
}
} catch (\Exception $e) {
@@ -390,8 +388,12 @@ class Router
*/
public function findRoute($name)
{
$max = count($this->processedRoutes) - 1;
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
for ($i = $max; $i >= 0; $i--) {
$route = $this->processedRoutes[$i];
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
if ($route->hasName($name)) {
@@ -445,13 +447,13 @@ class Router
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
* @throws InvalidArgumentException
* @throws \InvalidArgumentException
* @return string
*/
public function getUrl($name = null, $parameters = null, $getParams = null)
{
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');
}
if ($name === '' && $parameters === '') {
@@ -467,7 +469,7 @@ class Router
/* Return current route if no options has been specified */
if ($name === null && $parameters === null) {
return $this->request->getUrl()->getPath() . $this->arrayToParams($getParams);
return $this->request->getUri()->getPath() . $this->arrayToParams($getParams);
}
$loadedRoute = $this->request->getLoadedRoute();
@@ -490,8 +492,12 @@ class Router
/* Loop through all the routes to see if we can find a match */
$max = count($this->processedRoutes) - 1;
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
for ($i = $max; $i >= 0; $i--) {
$route = $this->processedRoutes[$i];
/* Check if the route contains the name/alias */
if ($route->hasName($controller) === true) {
@@ -539,16 +545,6 @@ class Router
$this->bootManagers[] = $bootManager;
}
/**
* Get routes that has been processed.
*
* @return array
*/
public function getProcessedRoutes()
{
return $this->processedRoutes;
}
/**
* @return array
*/
@@ -602,4 +598,4 @@ class Router
return $this;
}
}
}
+10 -32
View File
@@ -10,11 +10,11 @@
namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\CallbackExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Route\IRoute;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteController;
@@ -43,9 +43,9 @@ class SimpleRouter
protected static $router;
/**
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws HttpException
* @throws \Exception
* Start/route request
*
* @throws HttpException|NotFoundHttpException|\Exception
*/
public static function start()
{
@@ -66,7 +66,6 @@ class SimpleRouter
* Base CSRF verifier
*
* @param BaseCsrfVerifier $baseCsrfVerifier
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier)
{
@@ -78,7 +77,6 @@ class SimpleRouter
* Perfect if you want to load pretty-urls from a file or database.
*
* @param IRouterBootManager $bootManager
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function addBootManager(IRouterBootManager $bootManager)
{
@@ -91,9 +89,7 @@ class SimpleRouter
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
*
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function get($url, $callback, array $settings = null)
{
@@ -107,7 +103,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function post($url, $callback, array $settings = null)
{
@@ -121,7 +116,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function put($url, $callback, array $settings = null)
{
@@ -135,7 +129,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function patch($url, $callback, array $settings = null)
{
@@ -149,7 +142,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function options($url, $callback, array $settings = null)
{
@@ -163,7 +155,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function delete($url, $callback, array $settings = null)
{
@@ -175,14 +166,13 @@ class SimpleRouter
*
* @param array $settings
* @param \Closure $callback
* @throws \InvalidArgumentException
* @return RouteGroup
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException
*/
public static function group(array $settings = [], \Closure $callback)
{
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');
}
$group = new RouteGroup();
@@ -199,16 +189,15 @@ class SimpleRouter
* parameters and which are only rendered when the url matches.
*
* @param string $url
* @param \Closure $callback
* @param array $settings
* @param \Closure $callback
* @throws \InvalidArgumentException
* @return RoutePartialGroup
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException
*/
public static function partialGroup($url, \Closure $callback, array $settings = [])
{
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');
}
$settings['prefix'] = $url;
@@ -230,7 +219,6 @@ class SimpleRouter
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function basic($url, $callback, array $settings = null)
{
@@ -246,7 +234,6 @@ class SimpleRouter
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function form($url, $callback, array $settings = null)
{
@@ -261,7 +248,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function match(array $requestMethods, $url, $callback, array $settings = null)
{
@@ -285,7 +271,6 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function all($url, $callback, array $settings = null)
{
@@ -308,7 +293,6 @@ class SimpleRouter
* @param string $controller
* @param array|null $settings
* @return RouteController|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function controller($url, $controller, array $settings = null)
{
@@ -331,7 +315,6 @@ class SimpleRouter
* @param string $controller
* @param array|null $settings
* @return RouteResource|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function resource($url, $controller, array $settings = null)
{
@@ -352,7 +335,6 @@ class SimpleRouter
*
* @param \Closure $callback
* @return CallbackExceptionHandler $callbackHandler
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function error(\Closure $callback)
{
@@ -385,9 +367,8 @@ class SimpleRouter
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
* @throws \Pecee\Exceptions\InvalidArgumentException
* @throws \Exception
* @return string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function getUrl($name = null, $parameters = null, $getParams = null)
{
@@ -398,7 +379,6 @@ class SimpleRouter
* Get the request
*
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function request()
{
@@ -409,7 +389,6 @@ class SimpleRouter
* Get the response object
*
* @return Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function response()
{
@@ -424,7 +403,6 @@ class SimpleRouter
* Returns the router instance
*
* @return Router
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function router()
{
+1 -1
View File
@@ -7,7 +7,7 @@ class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
global $stack;
$stack[] = static::class;
$request->setUrl('/');
$request->setUri(new \Pecee\Http\Uri('/'));
return $request;
}
@@ -7,7 +7,7 @@ class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
global $stack;
$stack[] = static::class;
$request->setUrl('/');
$request->setUri(new \Pecee\Http\Uri('/'));
return $request;
}
@@ -1,16 +0,0 @@
<?php
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class RewriteMiddleware implements IMiddleware {
public function handle(Request $request) {
$request->setRewriteCallback(function() {
return 'ok';
});
}
}
+6 -6
View File
@@ -3,18 +3,18 @@
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
{
public static function debugNoReset($testUrl, $testMethod = 'get')
public static function debugNoReset($testUri, $testMethod = 'get')
{
static::request()->setUrl($testUrl);
static::request()->setUri(new \Pecee\Http\Uri($testUri));
static::request()->setMethod($testMethod);
static::start();
}
public static function debug($testUrl, $testMethod = 'get')
public static function debug($testUri, $testMethod = 'get')
{
try {
static::debugNoReset($testUrl, $testMethod);
static::debugNoReset($testUri, $testMethod);
} catch(\Exception $e) {
static::router()->reset();
throw $e;
@@ -24,13 +24,13 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
}
public static function debugOutput($testUrl, $testMethod = 'get')
public static function debugOutput($testUri, $testMethod = 'get')
{
$response = null;
// Route request
ob_start();
static::debug($testUrl, $testMethod);
static::debug($testUri, $testMethod);
$response = ob_get_contents();
ob_end_clean();
+5 -104
View File
@@ -5,7 +5,6 @@ require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Helpers/TestRouter.php';
require_once 'Dummy/Middlewares/RewriteMiddleware.php';
class RouteRewriteTest extends PHPUnit_Framework_TestCase
{
@@ -34,9 +33,9 @@ class RouteRewriteTest extends PHPUnit_Framework_TestCase
global $stack;
$stack = [];
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () use ($stack) {
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () {
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () use ($stack) {
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () {
TestRouter::get('/my-path', 'DummyController@method1');
@@ -65,8 +64,10 @@ class RouteRewriteTest extends PHPUnit_Framework_TestCase
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
if (strtolower($request->getUrl()->getPath()) === '/my/test/') {
if (strtolower($request->getUri()->getPath()) == '/my/test') {
$request->setRewriteUrl('/another-non-existing');
return $request;
}
});
@@ -74,104 +75,4 @@ class RouteRewriteTest extends PHPUnit_Framework_TestCase
TestRouter::debug('/my/test', 'get');
}
public function testRewriteUrlFromRoute()
{
TestRouter::get('/old', function () {
TestRouter::request()->setRewriteUrl('/new');
});
TestRouter::get('/new', function () {
echo 'ok';
});
TestRouter::get('/new1', function () {
echo 'ok';
});
TestRouter::get('/new2', function () {
echo 'ok';
});
$output = TestRouter::debugOutput('/old');
$this->assertEquals('ok', $output);
}
public function testRewriteCallbackFromRoute()
{
TestRouter::get('/old', function () {
TestRouter::request()->setRewriteUrl('/new');
});
TestRouter::get('/new', function () {
return 'ok';
});
TestRouter::get('/new1', function () {
return 'fail';
});
TestRouter::get('/new/2', function () {
return 'fail';
});
$output = TestRouter::debugOutput('/old');
TestRouter::router()->reset();
$this->assertEquals('ok', $output);
}
public function testRewriteRouteFromRoute()
{
TestRouter::get('/match', function () {
TestRouter::request()->setRewriteRoute(new \Pecee\SimpleRouter\Route\RouteUrl('/match', function () {
return 'ok';
}));
});
TestRouter::get('/old1', function () {
return 'fail';
});
TestRouter::get('/old/2', function () {
return 'fail';
});
TestRouter::get('/new2', function () {
return 'fail';
});
$output = TestRouter::debugOutput('/match');
TestRouter::router()->reset();
$this->assertEquals('ok', $output);
}
public function testMiddlewareRewrite()
{
TestRouter::group(['middleware' => 'RewriteMiddleware'], function () {
TestRouter::get('/', function () {
return 'fail';
});
TestRouter::get('no/match', function () {
return 'fail';
});
});
$output = TestRouter::debugOutput('/');
$this->assertEquals('ok', $output);
}
}
-14
View File
@@ -125,20 +125,6 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
TestRouter::debug('/my/custom-path', 'get');
}
public function testParameterDefaultValue() {
$defaultVariable = null;
TestRouter::get('/my/{path?}', function($path = 'working') use(&$defaultVariable) {
$defaultVariable = $path;
});
TestRouter::debug('/my/');
$this->assertEquals('working', $defaultVariable);
}
public function testDefaultParameterRegex()
{
TestRouter::get('/my/{path}', 'DummyController@param', ['defaultParameterRegex' => '[\w\-]+']);