mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 16:57:53 +00:00
Compare commits
18 Commits
1.7.4.1
...
development
| Author | SHA1 | Date | |
|---|---|---|---|
| 2d57b45c7b | |||
| 98cc8504d4 | |||
| 035a5b1629 | |||
| 832aff0358 | |||
| 43e05ad821 | |||
| 2fd32868c2 | |||
| e51b72f0e0 | |||
| 3b5e2aee9d | |||
| 27ba532b2d | |||
| a8620cbc70 | |||
| 4e054dccf5 | |||
| e7dfbb159c | |||
| 8c5a5327d1 | |||
| 3c9a675f25 | |||
| dfccd99f2f | |||
| 980a4e9b6a | |||
| fab0d0641c | |||
| 4169716f87 |
+2
-1
@@ -1,3 +1,4 @@
|
||||
.idea
|
||||
composer.lock
|
||||
vendor/
|
||||
vendor/
|
||||
demo-project/vendor
|
||||
@@ -32,6 +32,14 @@ The goal of this project is to create a router that is 100% compatible with the
|
||||
- Custom boot managers to redirect urls to other routes
|
||||
- Input manager; to manage `GET`, `POST` params.
|
||||
|
||||
## Installation and demo
|
||||
|
||||
We've included a simple demo project for the router which can be found in the `demo-project` folder.
|
||||
|
||||
Please refer to the demo-project documentation for further reading on how to setup and install simple-php-router:
|
||||
|
||||
[Link to demo documentation](demo-project/README.md)
|
||||
|
||||
## Initialising the router
|
||||
|
||||
In your ```index.php``` require your ```routes.php``` and call the ```routeRequest()``` method when all your custom routes has been loaded. This will trigger and do the actual routing of the requests.
|
||||
@@ -108,7 +116,7 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So
|
||||
This is a basic example of an ExceptionHandler implementation:
|
||||
|
||||
```php
|
||||
namespace BB\Handlers;
|
||||
namespace Demo\Handlers;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\RouterEntry;
|
||||
@@ -132,7 +140,7 @@ class CustomExceptionHandler implements IExceptionHandler {
|
||||
}
|
||||
|
||||
}
|
||||
``
|
||||
```
|
||||
|
||||
### Sub-domain routing
|
||||
|
||||
@@ -176,93 +184,21 @@ This is a simple example of an integration into a framework.
|
||||
The framework has it's own ```Router``` class which inherits from the ```SimpleRouter``` class. This allows the framework to add custom functionality.
|
||||
|
||||
```php
|
||||
<?php
|
||||
<?php
|
||||
namespace Pecee;
|
||||
namespace Demo;
|
||||
|
||||
use Pecee\Exception\RouterException;
|
||||
use Pecee\Handler\ExceptionHandler;
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\SimpleRouter\RouterBase;
|
||||
use Pecee\SimpleRouter\SimpleRouter;
|
||||
|
||||
class Router extends SimpleRouter {
|
||||
|
||||
protected static $defaultExceptionHandler;
|
||||
protected static $defaultMiddlewares = array();
|
||||
|
||||
public static function start($defaultNamespace = null) {
|
||||
|
||||
// Debug information
|
||||
Debug::getInstance()->add('Router initialised.');
|
||||
// change this to whatever makes sense in your project
|
||||
require_once 'routes.php';
|
||||
|
||||
// Load framework specific controllers
|
||||
static::get('/js-wrap', 'ControllerJs@wrap', ['namespace' => '\Pecee\Controller'])->setAlias('pecee.js.wrap');
|
||||
static::get('/css-wrap', 'ControllerCss@wrap', ['namespace' => '\Pecee\Controller'])->setAlias('pecee.css.wrap');
|
||||
static::get('/captcha', 'ControllerCaptcha@show', ['namespace' => '\Pecee\Controller']);
|
||||
// Do initial stuff
|
||||
|
||||
// Load routes.php
|
||||
$file = $_ENV['base_path'] . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'routes.php';
|
||||
if(file_exists($file)) {
|
||||
require_once $file;
|
||||
}
|
||||
parent::start('\\Demo\\Controllers');
|
||||
|
||||
// Set default namespace
|
||||
$defaultNamespace = '\\'.$_ENV['app_name'] . '\\Controller';
|
||||
|
||||
// Handle exceptions
|
||||
try {
|
||||
|
||||
if(count(static::$defaultMiddlewares)) {
|
||||
/* @var $middleware \Pecee\Http\Middleware\IMiddleware */
|
||||
foreach(static::$defaultMiddlewares as $middleware) {
|
||||
$middleware = new $middleware();
|
||||
if(!($middleware instanceof IMiddleware)) {
|
||||
throw new RouterException('Middleware must be implement the IMiddleware interface.');
|
||||
}
|
||||
$middleware->handle(RouterBase::getInstance()->getRequest());
|
||||
}
|
||||
}
|
||||
|
||||
parent::start($defaultNamespace);
|
||||
} catch(\Exception $e) {
|
||||
|
||||
$route = RouterBase::getInstance()->getLoadedRoute();
|
||||
|
||||
// Otherwise use the fallback default exceptions handler
|
||||
if(static::$defaultExceptionHandler !== null) {
|
||||
static::loadExceptionHandler(static::$defaultExceptionHandler, $route, $e);
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected static function loadExceptionHandler($class, $route, $e) {
|
||||
$class = new $class();
|
||||
|
||||
if(!($class instanceof ExceptionHandler)) {
|
||||
throw new \ErrorException('Exception handler must be an instance of \Pecee\Handler\ExceptionHandler');
|
||||
}
|
||||
|
||||
$class->handleError(RouterBase::getInstance()->getRequest(), $route, $e);
|
||||
}
|
||||
|
||||
public static function defaultExceptionHandler($handler) {
|
||||
static::$defaultExceptionHandler = $handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add default middleware that will be loaded before any route
|
||||
* @param string|array $middlewares
|
||||
*/
|
||||
public static function defaultMiddleware($middlewares) {
|
||||
if(is_array($middlewares)) {
|
||||
static::$defaultMiddlewares = $middlewares;
|
||||
} else {
|
||||
static::$defaultMiddlewares[] = $middlewares;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -342,7 +278,6 @@ Sometimes it can be necessary to keep urls stored in the database, file or simil
|
||||
To interfere with the router, we create a class that inherits from ```RouterBootManager```. This class will be loaded before any other rules in ```routes.php``` and allow us to "change" the current route, if any of our criteria are fulfilled (like coming from the url ```/my-cat-is-beatiful```).
|
||||
|
||||
```php
|
||||
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\RouterBootManager;
|
||||
|
||||
@@ -482,6 +417,7 @@ This is some sites that uses the simple-router project in production.
|
||||
- [holla.dk](http://www.holla.dk)
|
||||
- [ninjaimg.com](http://ninjaimg.com)
|
||||
- [bookandbegin.com](https://bookandbegin.com)
|
||||
- [dscuz.com](https://www.dscuz.com)
|
||||
|
||||
## Documentation
|
||||
While I work on a better documentation, please refer to the Laravel 5 routing documentation here:
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# Simple PHP router demo project
|
||||
|
||||
This project is here to give you a basic understanding of how to setup and using simple-php-router.
|
||||
|
||||
Please note that this demo-project only covers how to integrate the `simple-php-router` in a project without a framework. If you are using some sort of PHP framework in your project the implementation might vary.
|
||||
|
||||
**What we won't cover:**
|
||||
|
||||
- How to setup a solution that fits your need. This is a basic demo to help you get started.
|
||||
- Understanding of MVC; including Controllers, Middlewares or ExceptionHandlers.
|
||||
- How to integrate into third party frameworks.
|
||||
|
||||
**What we cover:**
|
||||
|
||||
- How to get up and running fast - from scratch.
|
||||
- How to get ExceptionHandlers, Middlewares and Controllers working.
|
||||
- How to setup your webservers.
|
||||
|
||||
## Installation
|
||||
|
||||
- Navigate to the `demo-project` folder in terminal and run `composer update` to install the latest version.
|
||||
- Point your webserver to `demo-project/public`.
|
||||
|
||||
### Setting up Nginx
|
||||
|
||||
If you are using Nginx please make sure that url-rewriting is enabled.
|
||||
|
||||
You can easily enable url-rewriting by adding the following configuration for the Nginx configuration-file for the demo-project.
|
||||
|
||||
```
|
||||
location / {
|
||||
try_files $uri $uri/ /index.php?$query_string;
|
||||
}
|
||||
```
|
||||
|
||||
### Setting up Apache
|
||||
|
||||
Nothing special is required for Apache to work. We've include the `.htaccess` file in the `public` folder. If rewriting is not working for you, please check that the `mod_rewrite` module (htaccess support) is enabled in the Apache configuration.
|
||||
|
||||
## Folder structure
|
||||
|
||||
| Folder | Description |
|
||||
| ------------- |-------------|
|
||||
| app |Contains projects-specific PHP classes|
|
||||
| public |Public folder which are accessible through the web.|
|
||||
|
||||
## Notes
|
||||
|
||||
The demo project has it's own `Router` class implementation which extends the `SimpleRouter` class with further functionality.
|
||||
This class can be useful adding additional functionality that are required before and after routing occurs or any extra functionality belonging to the router itself.
|
||||
|
||||
In this project we also use our custom router-class to autoload the `routes.php` file from our custom location (`app/routes.php`).
|
||||
|
||||
Please check the `routes.php` file in `demo-project/app` for all the urls/rules available in the project.
|
||||
|
||||
### CSRF-verifier
|
||||
|
||||
For the purpose of this demo, we've added a custom CSRF-verifier middleware called `CsrfVerifier` and disabled CSRF checks for all calls to `/api/*`. This will ensure that CSRF form-checks are not applied when calling our demo api url.
|
||||
|
||||
### Exception handlers
|
||||
|
||||
The included `CustomExceptionHandler` class returns a very basic json response for errors received on calls to `/api/*` or otherwise just a simple formatted error response.
|
||||
|
||||
### Middlewares
|
||||
|
||||
`ApiVerification` class is added to all calls to `/api/*`. This simple class just adds some data to the `Request` object, which is returned in one of the methods in the `ApiController` class. We've added this class to demonstrate that you can use middlewares to ensure that the user has the correct authentication - before router loads the controller itself.
|
||||
|
||||
### Urls
|
||||
|
||||
Please see `routes.php` for all routes and rules.
|
||||
|
||||
| URL |
|
||||
| ------------- |
|
||||
| / |
|
||||
| /api/demo |
|
||||
| /companies |
|
||||
| /companies/[id] |
|
||||
| /contact |
|
||||
|
||||
## The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Simon Sessingø / simple-php-router
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
namespace Demo\Controllers;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class ApiController {
|
||||
|
||||
public function index() {
|
||||
|
||||
// The variable authenticated is set to true in the ApiVerification middleware class.
|
||||
|
||||
$request = Request::getInstance();
|
||||
|
||||
header('content-type: application/json');
|
||||
|
||||
echo json_encode([
|
||||
'authenticated' => $request->authenticated
|
||||
]);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
namespace Demo\Controllers;
|
||||
|
||||
class DefaultController {
|
||||
|
||||
public function index() {
|
||||
|
||||
// implement
|
||||
echo 'DefaultController -> index';
|
||||
|
||||
}
|
||||
|
||||
public function contact() {
|
||||
|
||||
echo 'DefaultController -> contact';
|
||||
|
||||
}
|
||||
|
||||
public function companies($id = null) {
|
||||
|
||||
echo 'DefaultController -> companies -> id: ' . $id;
|
||||
|
||||
}
|
||||
|
||||
public function notFound() {
|
||||
echo 'Page not found';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
namespace Demo\Handlers;
|
||||
|
||||
use Pecee\Handler\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\RouterEntry;
|
||||
|
||||
class CustomExceptionHandler implements IExceptionHandler {
|
||||
|
||||
public function handleError( Request $request, RouterEntry $router = null, \Exception $error) {
|
||||
|
||||
// Return json errors if we encounter an error on /api.
|
||||
if(stripos($request->getUri(), '/api') !== false) {
|
||||
header('content-type: application/json');
|
||||
echo json_encode([
|
||||
'error' => $error->getMessage(),
|
||||
'code' => $error->getCode()
|
||||
]);
|
||||
die();
|
||||
}
|
||||
|
||||
// else we just throw the error
|
||||
if($error->getCode() == 404) {
|
||||
|
||||
// Return 404 path
|
||||
$request->setUri('/404');
|
||||
return $request;
|
||||
|
||||
}
|
||||
|
||||
throw $error;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class ApiVerification implements IMiddleware {
|
||||
|
||||
public function handle(Request $request) {
|
||||
|
||||
// Do authentication
|
||||
$request->authenticated = true;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
|
||||
class CsrfVerifier extends BaseCsrfVerifier {
|
||||
|
||||
/**
|
||||
* CSRF validation will be ignored on the following urls.
|
||||
*/
|
||||
protected $except = ['/api/*'];
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Custom router which handles default middlewares, default exceptions and things
|
||||
* that should be happen before and after the router is initialised.
|
||||
*/
|
||||
|
||||
namespace Demo;
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter;
|
||||
|
||||
class Router extends SimpleRouter {
|
||||
|
||||
public static function start($defaultNamespace = null) {
|
||||
|
||||
// change this to whatever makes sense in your project
|
||||
require_once 'routes.php';
|
||||
|
||||
// Do initial stuff
|
||||
|
||||
parent::start('\\Demo\\Controllers');
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains all the routes for the project
|
||||
*/
|
||||
|
||||
use Demo\Router;
|
||||
|
||||
Router::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
|
||||
|
||||
Router::group(['exceptionHandler' => 'Demo\Handlers\CustomExceptionHandler'], function() {
|
||||
|
||||
Router::get('/', 'DefaultController@index')->setAlias('home');
|
||||
Router::get('/contact', 'DefaultController@contact')->setAlias('contact');
|
||||
Router::get('/404', 'DefaultController@notFound')->setAlias('404');
|
||||
Router::basic('/companies', 'DefaultController@companies')->setAlias('companies');
|
||||
Router::basic('/companies/{id}', 'DefaultController@companies')->setAlias('companies');
|
||||
|
||||
// Api
|
||||
Router::group(['prefix' => '/api', 'middleware' => 'Demo\Middlewares\ApiVerification'], function() {
|
||||
Router::resource('/demo', 'ApiController');
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "pecee/simple-router-demo",
|
||||
"description": "Simple router demo project",
|
||||
"keywords": [
|
||||
"simple-router",
|
||||
"php",
|
||||
"php-simple-router"
|
||||
],
|
||||
"license": "MIT",
|
||||
"type": "project",
|
||||
"require": {
|
||||
"php": ">=5.4.0",
|
||||
"pecee/simple-router": "1.*"
|
||||
},
|
||||
"require-dev": {
|
||||
|
||||
},
|
||||
"config": {
|
||||
"preferred-install": "dist"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Demo\\": "app/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
RewriteEngine on
|
||||
RewriteCond %{SCRIPT_FILENAME} !-f
|
||||
RewriteCond %{SCRIPT_FILENAME} !-d
|
||||
RewriteCond %{SCRIPT_FILENAME} !-l
|
||||
RewriteRule ^(.*)$ index.php/$1
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
// load composer dependencies
|
||||
require '../vendor/autoload.php';
|
||||
|
||||
// Start the routing
|
||||
\Demo\Router::start();
|
||||
@@ -96,7 +96,10 @@ class Request {
|
||||
* @return string
|
||||
*/
|
||||
public function getIp() {
|
||||
return ((isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strlen($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
|
||||
if(isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
|
||||
return $_SERVER['HTTP_CF_CONNECTING_IP'];
|
||||
}
|
||||
return ((isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strlen($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -86,15 +86,22 @@ class RouterBase {
|
||||
$this->currentRoute = $route;
|
||||
|
||||
if($route instanceof RouterGroup && is_callable($route->getCallback())) {
|
||||
$group = $route;
|
||||
|
||||
$group->renderRoute($this->request);
|
||||
$mergedSettings = array_merge($settings, $group->getMergeableSettings());
|
||||
$route->renderRoute($this->request);
|
||||
|
||||
if($route->matchRoute($this->request)) {
|
||||
|
||||
$group = $route;
|
||||
|
||||
$mergedSettings = array_merge($settings, $group->getMergeableSettings());
|
||||
|
||||
// Add ExceptionHandler
|
||||
if ($group->getExceptionHandler() !== null) {
|
||||
$this->exceptionHandlers[] = $route;
|
||||
}
|
||||
|
||||
// Add ExceptionHandler
|
||||
if($group->matchRoute($this->request) && $group->getExceptionHandler() !== null) {
|
||||
$this->exceptionHandlers[] = $route;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$this->currentRoute = null;
|
||||
@@ -109,64 +116,68 @@ class RouterBase {
|
||||
}
|
||||
}
|
||||
|
||||
public function routeRequest() {
|
||||
public function routeRequest($original = true) {
|
||||
|
||||
$originalUri = $this->request->getUri();
|
||||
|
||||
// Initialize boot-managers
|
||||
if(count($this->bootManagers)) {
|
||||
/* @var $manager RouterBootManager */
|
||||
foreach($this->bootManagers as $manager) {
|
||||
$this->request = $manager->boot($this->request);
|
||||
|
||||
if(!($this->request instanceof Request)) {
|
||||
throw new RouterException('Custom router bootmanager "'. get_class($manager) .'" must return instance of Request.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify csrf token for request
|
||||
if($this->baseCsrfVerifier !== null) {
|
||||
$this->baseCsrfVerifier->handle($this->request);
|
||||
}
|
||||
|
||||
// Loop through each route-request
|
||||
$this->processRoutes($this->routes);
|
||||
|
||||
$routeNotAllowed = false;
|
||||
|
||||
$max = count($this->controllerUrlMap);
|
||||
try {
|
||||
|
||||
/* @var $route RouterEntry */
|
||||
for($i = 0; $i < $max; $i++) {
|
||||
// Initialize boot-managers
|
||||
if(count($this->bootManagers)) {
|
||||
/* @var $manager RouterBootManager */
|
||||
foreach($this->bootManagers as $manager) {
|
||||
$this->request = $manager->boot($this->request);
|
||||
|
||||
$route = $this->controllerUrlMap[$i];
|
||||
|
||||
$routeMatch = $route->matchRoute($this->request);
|
||||
|
||||
if($routeMatch) {
|
||||
|
||||
if(count($route->getRequestMethods()) && !in_array($this->request->getMethod(), $route->getRequestMethods())) {
|
||||
$routeNotAllowed = true;
|
||||
continue;
|
||||
if(!($this->request instanceof Request)) {
|
||||
throw new RouterException('Custom router bootmanager "'. get_class($manager) .'" must return instance of Request.');
|
||||
}
|
||||
}
|
||||
|
||||
$routeNotAllowed = false;
|
||||
|
||||
$this->request->rewrite_uri = $this->request->uri;
|
||||
$this->request->setUri($originalUri);
|
||||
|
||||
$this->request->loadedRoute = $route;
|
||||
$route->loadMiddleware($this->request);
|
||||
|
||||
try {
|
||||
$this->request->loadedRoute->renderRoute($this->request);
|
||||
} catch(\Exception $e) {
|
||||
$this->handleException($e);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// Loop through each route-request
|
||||
$this->processRoutes($this->routes);
|
||||
|
||||
if($original === true) {
|
||||
// Verify csrf token for request
|
||||
if ($this->baseCsrfVerifier !== null) {
|
||||
$this->baseCsrfVerifier->handle($this->request);
|
||||
}
|
||||
}
|
||||
|
||||
$max = count($this->controllerUrlMap);
|
||||
|
||||
/* @var $route RouterEntry */
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
|
||||
$route = $this->controllerUrlMap[$i];
|
||||
|
||||
$routeMatch = $route->matchRoute($this->request);
|
||||
|
||||
if ($routeMatch) {
|
||||
|
||||
if (count($route->getRequestMethods()) && !in_array($this->request->getMethod(), $route->getRequestMethods())) {
|
||||
$routeNotAllowed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
$routeNotAllowed = false;
|
||||
|
||||
$this->request->rewrite_uri = $this->request->uri;
|
||||
$this->request->setUri($originalUri);
|
||||
|
||||
$this->request->loadedRoute = $route;
|
||||
$route->loadMiddleware($this->request);
|
||||
|
||||
$this->request->loadedRoute->renderRoute($this->request);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} catch(\Exception $e) {
|
||||
$this->handleException($e);
|
||||
}
|
||||
|
||||
if($routeNotAllowed) {
|
||||
@@ -180,6 +191,8 @@ class RouterBase {
|
||||
|
||||
protected function handleException(\Exception $e) {
|
||||
|
||||
$request = null;
|
||||
|
||||
/* @var $route RouterGroup */
|
||||
foreach ($this->exceptionHandlers as $route) {
|
||||
$route->loadMiddleware($this->request);
|
||||
@@ -190,7 +203,13 @@ class RouterBase {
|
||||
throw new RouterException('Exception handler must implement the IExceptionHandler interface.');
|
||||
}
|
||||
|
||||
$handler->handleError($this->request, $this->request->loadedRoute, $e);
|
||||
$request = $handler->handleError($this->request, $this->request->loadedRoute, $e);
|
||||
}
|
||||
|
||||
if($request !== null) {
|
||||
$this->request = $request;
|
||||
$this->routeRequest(false);
|
||||
return;
|
||||
}
|
||||
|
||||
throw $e;
|
||||
@@ -291,15 +310,16 @@ class RouterBase {
|
||||
|
||||
public function arrayToParams(array $getParams = null, $includeEmpty = true) {
|
||||
|
||||
if(is_array($getParams)) {
|
||||
if(is_array($getParams) && count($getParams)) {
|
||||
if ($includeEmpty === false) {
|
||||
$getParams = array_filter($getParams, function ($item) {
|
||||
return (!empty($item));
|
||||
});
|
||||
}
|
||||
|
||||
return http_build_query($getParams);
|
||||
return '?' . http_build_query($getParams);
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -354,8 +374,8 @@ class RouterBase {
|
||||
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
if($getParams !== null && count($getParams)) {
|
||||
$url .= '?' . $this->arrayToParams($getParams);
|
||||
if($getParams !== null) {
|
||||
$url .= $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
@@ -377,8 +397,8 @@ class RouterBase {
|
||||
|
||||
$url = parse_url($this->request->getUri(), PHP_URL_PATH);
|
||||
|
||||
if(count($getParams)) {
|
||||
$url .= '?' . $this->arrayToParams($getParams);
|
||||
if($getParams !== null) {
|
||||
$url .= $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
@@ -449,22 +469,18 @@ class RouterBase {
|
||||
|
||||
$url = '/' . trim(join('/', $url), '/') . '/';
|
||||
|
||||
if($getParams !== null && count($getParams)) {
|
||||
$url .= '?' . $this->arrayToParams($getParams);
|
||||
if($getParams !== null) {
|
||||
$url .= $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
if(self::$instance === null) {
|
||||
self::$instance = new static();
|
||||
if(static::$instance === null) {
|
||||
static::$instance = new static();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public static function reset() {
|
||||
self::$instance = null;
|
||||
return static::$instance;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -301,7 +301,7 @@ abstract class RouterEntry {
|
||||
|
||||
$parameterValues = array();
|
||||
|
||||
if(preg_match('/^'.$regex.'$/is', $url, $parameterValues)) {
|
||||
if(preg_match('/^'.$regex.'\/?$/is', $url, $parameterValues)) {
|
||||
|
||||
$parameters = array();
|
||||
|
||||
@@ -310,7 +310,7 @@ abstract class RouterEntry {
|
||||
if($max) {
|
||||
for($i = 0; $i < $max; $i++) {
|
||||
$name = $parameterNames[$i];
|
||||
$parameterValue = (isset($parameterValues[$name['name']]) && !empty($parameterValues[$name['name']])) ? $parameterValues[$name['name']] : null;
|
||||
$parameterValue = isset($parameterValues[$name['name']]) ? $parameterValues[$name['name']] : null;
|
||||
|
||||
if($name['required'] && $parameterValue === null) {
|
||||
throw new RouterException('Missing required parameter ' . $name['name'], 404);
|
||||
|
||||
@@ -93,9 +93,23 @@ class RouterGroup extends RouterEntry {
|
||||
unset($settings['namespace']);
|
||||
}
|
||||
|
||||
// Push middleware if multiple
|
||||
if($this->getMiddleware() !== null && isset($settings['middleware'])) {
|
||||
|
||||
if(!is_array($this->getMiddleware())) {
|
||||
$middlewares = [$this->getMiddleware(), $settings['middleware']];
|
||||
} else {
|
||||
$middlewares = array_push($settings['middleware']);
|
||||
}
|
||||
|
||||
$settings['middleware'] = array_unique(array_reverse($middlewares));
|
||||
|
||||
}
|
||||
|
||||
if(is_array($settings)) {
|
||||
$this->settings = array_merge($this->settings, $settings);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class RouterResource extends RouterEntry {
|
||||
|
||||
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
|
||||
|
||||
$parameters = $this->parseParameters($route, $url, '[0-9]+?');
|
||||
$parameters = $this->parseParameters($route, $url);
|
||||
|
||||
if($parameters !== null) {
|
||||
|
||||
|
||||
@@ -11,4 +11,8 @@ class DummyController {
|
||||
echo 'Params: ' . join(', ', $params);
|
||||
}
|
||||
|
||||
public function notFound() {
|
||||
echo 'not found';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
class ExceptionHandler implements \Pecee\Handler\IExceptionHandler {
|
||||
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\RouterEntry $router = null, \Exception $error){
|
||||
throw $error;
|
||||
}
|
||||
|
||||
}
|
||||
+2
-10
@@ -7,19 +7,11 @@ class GroupTest extends PHPUnit_Framework_TestCase {
|
||||
|
||||
protected $result;
|
||||
|
||||
public function __construct() {
|
||||
// Initial setup
|
||||
$_SERVER['HTTP_HOST'] = 'example.com';
|
||||
$_SERVER['REQUEST_URI'] = '/api/v1/test';
|
||||
$_SERVER['REQUEST_METHOD'] = 'get';
|
||||
}
|
||||
|
||||
protected function group() {
|
||||
$this->result = true;
|
||||
}
|
||||
|
||||
public function testGroup() {
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
$this->result = false;
|
||||
|
||||
@@ -35,9 +27,9 @@ class GroupTest extends PHPUnit_Framework_TestCase {
|
||||
}
|
||||
|
||||
public function testNestedGroup() {
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setUri('/api/v1/test');
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setUri('/api/v1/test');
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setMethod('get');
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::group(['prefix' => '/api'], function() {
|
||||
\Pecee\SimpleRouter\SimpleRouter::group(['prefix' => '/v1'], function() {
|
||||
|
||||
+6
-11
@@ -2,29 +2,24 @@
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
|
||||
class MiddlewareTest extends PHPUnit_Framework_TestCase {
|
||||
|
||||
public function __construct() {
|
||||
// Initial setup
|
||||
$_SERVER['HTTP_HOST'] = 'example.com';
|
||||
$_SERVER['REQUEST_URI'] = '/my/test/url';
|
||||
$_SERVER['REQUEST_METHOD'] = 'get';
|
||||
}
|
||||
|
||||
public function testMiddlewareFound() {
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setMethod('get');
|
||||
\Pecee\Http\Request::getInstance()->setUri('/my/test/url');
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
|
||||
\Pecee\SimpleRouter\SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function() {
|
||||
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
|
||||
});
|
||||
|
||||
$found = false;
|
||||
|
||||
try {
|
||||
\Pecee\SimpleRouter\SimpleRouter::start();
|
||||
}catch(Exception $e) {
|
||||
}catch(\Exception $e) {
|
||||
$found = ($e instanceof MiddlewareLoadedException);
|
||||
}
|
||||
|
||||
|
||||
+27
-23
@@ -2,58 +2,68 @@
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
|
||||
class RouterRouteTest extends PHPUnit_Framework_TestCase {
|
||||
|
||||
|
||||
public function testNotFound() {
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setMethod('get');
|
||||
\Pecee\Http\Request::getInstance()->setUri('/test-param1-param2');
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function() {
|
||||
\Pecee\SimpleRouter\SimpleRouter::get('/non-existing-path', 'DummyController@start');
|
||||
});
|
||||
|
||||
$found = false;
|
||||
|
||||
try {
|
||||
\Pecee\SimpleRouter\SimpleRouter::start();
|
||||
}catch(\Exception $e) {
|
||||
$found = ($e instanceof \Pecee\Exception\RouterException && $e->getCode() == 404);
|
||||
}
|
||||
|
||||
$this->assertTrue($found);
|
||||
|
||||
public function __construct() {
|
||||
// Initial setup
|
||||
$_SERVER['HTTP_HOST'] = 'example.com';
|
||||
$_SERVER['REQUEST_URI'] = '/my/test/url';
|
||||
$_SERVER['REQUEST_METHOD'] = 'get';
|
||||
}
|
||||
|
||||
public function testGet() {
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setMethod('get');
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setUri('/my/test/url');
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setMethod('get');
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
\Pecee\SimpleRouter\SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testPost() {
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setUri('/my/test/url');
|
||||
\Pecee\Http\Request::getInstance()->setMethod('post');
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::post('/my/test/url', 'DummyController@start');
|
||||
\Pecee\SimpleRouter\SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testPut() {
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setUri('/my/test/url');
|
||||
\Pecee\Http\Request::getInstance()->setMethod('put');
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::put('/my/test/url', 'DummyController@start');
|
||||
\Pecee\SimpleRouter\SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testDelete() {
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setUri('/my/test/url');
|
||||
\Pecee\Http\Request::getInstance()->setMethod('delete');
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::delete('/my/test/url', 'DummyController@start');
|
||||
\Pecee\SimpleRouter\SimpleRouter::start();
|
||||
|
||||
}
|
||||
|
||||
public function testMethodNotAllowed() {
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::getInstance()->getRequest()->setUri('/my/test/url');
|
||||
\Pecee\Http\Request::getInstance()->setMethod('post');
|
||||
|
||||
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
@@ -68,8 +78,6 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase {
|
||||
|
||||
public function testSimpleParam() {
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setMethod('get');
|
||||
\Pecee\Http\Request::getInstance()->setUri('/test-param1');
|
||||
|
||||
@@ -80,8 +88,6 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase {
|
||||
|
||||
public function testMultiParam() {
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setMethod('get');
|
||||
\Pecee\Http\Request::getInstance()->setUri('/test-param1-param2');
|
||||
|
||||
@@ -92,8 +98,6 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase {
|
||||
|
||||
public function testPathParam() {
|
||||
|
||||
\Pecee\SimpleRouter\RouterBase::reset();
|
||||
|
||||
\Pecee\Http\Request::getInstance()->setMethod('get');
|
||||
\Pecee\Http\Request::getInstance()->setUri('/test/path/param1');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user