Compare commits

..

16 Commits

Author SHA1 Message Date
Simon Sessingø 8b3d71a328 Merge pull request #87 from skipperbent/development
[BUGFIX] Fixed only match group route if prefix is set
2016-04-09 10:02:22 +02:00
Simon Sessingø 1fae638aaf Merge pull request #86 from skipperbent/development
Development
2016-04-09 09:50:56 +02:00
Simon Sessingø 37c8bc9f32 Merge pull request #79 from skipperbent/development
[BUGFIX] Bugfixes and optimisations
2016-04-07 23:21:13 +02:00
Simon Sessingø 75029b330a Merge pull request #78 from skipperbent/development
[BUGFIX] Fixed nested groups not merging settings to routes
2016-04-07 19:34:02 +02:00
Simon Sessingø fd5d893040 Merge pull request #77 from skipperbent/development
[TASK] Added rewrite_uri parameter to Request class
2016-03-19 19:12:42 +01:00
Simon Sessingø c1512740af Merge pull request #76 from skipperbent/development
[BUGFIX] Readded rendering of groups
2016-03-19 18:59:01 +01:00
Simon Sessingø 212ae133de Merge pull request #75 from skipperbent/development
[TASK] Readded merging
2016-03-19 17:40:26 +01:00
Simon Sessingø ae58231fa1 Merge pull request #74 from skipperbent/development
Custom boot-managers
2016-03-19 16:29:03 +01:00
Simon Sessingø 358b25d4f1 Merge pull request #73 from skipperbent/development
Development
2016-03-18 17:55:31 +01:00
Simon Sessingø 3d45851d9b Merge pull request #72 from skipperbent/development
[BUGFIX] Only render group if prefix matches.
2016-03-16 19:58:03 +01:00
Simon Sessingø ee5c2207f8 Merge pull request #71 from skipperbent/development
Added support for x-forwarded-proto http header
2016-03-14 01:08:25 +01:00
Simon Sessingø b1ca3fc9ef Merge pull request #70 from skipperbent/development
[FEATURE] Added http code to redirect method.
2016-03-14 00:59:09 +01:00
Simon Sessingø 253c0c70d4 Merge pull request #69 from skipperbent/development
[BUGFIX] Bugfix
2016-03-01 22:52:38 +01:00
Simon Sessingø 53ba2d7ac5 Merge pull request #68 from skipperbent/development
[TASK] Fixed regex causing optional parameters to sometimes catch req…
2016-01-23 16:12:27 +01:00
Simon Sessingø 315fe05769 Merge pull request #67 from skipperbent/development
Development
2016-01-17 04:57:39 +01:00
Simon Sessingø a57113309a Merge pull request #66 from skipperbent/development
Development
2016-01-15 11:56:04 +01:00
31 changed files with 274 additions and 1197 deletions
+1 -2
View File
@@ -1,4 +1,3 @@
.idea
composer.lock
vendor/
demo-project/vendor
vendor/
+36 -139
View File
@@ -30,15 +30,6 @@ The goal of this project is to create a router that is 100% compatible with the
- Optional parameters
- Sub-domain routing
- 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
@@ -111,37 +102,6 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So
});
```
#### ExceptionHandler example
This is a basic example of an ExceptionHandler implementation:
```php
namespace Demo\Handlers;
use Pecee\Http\Request;
use Pecee\SimpleRouter\RouterEntry;
class CustomExceptionHandler implements IExceptionHandler {
public function handleError( Request $request, RouterEntry $router = null, \Exception $error) {
// If the error-code is 404; show another route which contains the page-not-found
if($error->getCode() === 404) {
// Load your custom 404-page view
}
// Output error as json if on api path.
if(stripos($request->getUri(), '/api') !== false) {
response()->json(['error' => $error->getMessage()]);
}
// Otherwise default exception will be thrown by the router.
}
}
```
### Sub-domain routing
Route groups may also be used to route wildcard sub-domains. 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:
@@ -184,21 +144,43 @@ 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
namespace Demo;
namespace MyProject;
use Pecee\Handler\ExceptionHandler;
use Pecee\SimpleRouter\RouterBase;
use Pecee\SimpleRouter\SimpleRouter;
class Router extends SimpleRouter {
protected static $defaultExceptionHandler;
public static function start($defaultNamespace = null) {
// change this to whatever makes sense in your project
require_once 'routes.php';
// Load routes.php
$file = $_ENV['base_path'] . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'routes.php';
if(file_exists($file)) {
require_once $file;
}
// Do initial stuff
// Set default namespace
$defaultNamespace = '\\'.$_ENV['app_name'] . '\\Controller';
parent::start('\\Demo\\Controllers');
// Handle exceptions
try {
parent::start($defaultNamespace);
} catch(\Exception $e) {
if(self::$defaultExceptionHandler !== null) {
$class = new self::$defaultExceptionHandler();
$class->handleError(RouterBase::getInstance()->getRequest(), $route, $e);
}
throw $e;
}
}
public static function setDefaultExceptionHandler($handler) {
self::$defaultExceptionHandler = $handler;
}
}
@@ -208,12 +190,15 @@ class Router extends SimpleRouter {
**This is a basic example of a helper function for generating urls.**
```php
use Pecee\SimpleRouter\SimpleRouter;
use Pecee\SimpleRouter\RouterBase;
function url($controller, $parameters = null, $getParams = null) {
SimpleRouter::getRoute($controller, $parameters, $getParams);
RouterBase::getInstance()->getRoute($controller, $parameters, $getParams);
}
```
**This is a basic example for getting the current csrf token**
```php
/**
* Get current csrf-token
* @return null|string
@@ -222,22 +207,6 @@ function csrf_token() {
$token = new \Pecee\CsrfToken();
return $token->getToken();
}
/**
* Get request object
* @return \Pecee\Http\Request
*/
function request() {
return SimpleRouter::request();
}
/**
* Get response object
* @return \Pecee\Http\Response
*/
function response() {
return SimpleRouter::response();
}
```
## Getting urls
@@ -291,6 +260,7 @@ 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;
@@ -340,14 +310,12 @@ SimpleRouter::get('/article/view/{id}', 'ControllerArticle@view');
## Easily overwrite route about to be loaded
Sometimes it can be useful to manipulate the route that's about to be loaded, for instance if a user is not authenticated or if an error occurred within your Middleware that requires
some other route to be initialised. 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\Http\Request``` object. All information about the current route is as a ```\Pecee\SimpleRouter\Http\Request``` object which can always be obtained on
the `RouterBase` instance. For easy access you can use the shortcut method `\Pecee\SimpleRouter\SimpleRouter::request()`.
the ```\Pecee\SimpleRouter\Http\Request``` object.
**Note:** Please note that it's only possible to change the route BEFORE any route has initially been loaded, so doing this in your custom ExceptionHandler or Middleware is highly recommended.
```php
use Pecee\SimpleRouter;
$route = SimpleRouter::request()->getLoadedRoute();
$route = Request::getInstance()->getLoadedRoute();
$route->setCallback('Example\MyCustomClass@hello');
@@ -357,82 +325,11 @@ $route->setClass('Example\MyCustomClass');
$route->setMethod('hello');
```
## Using the Input class to manage parameters
We've added the `Input` class to easy access parameters from your Controller-classes.
**Return single parameter value (matches both GET, POST, FILE):**
```php
$value = SimpleRouter::request()->getInput()->get('name');
```
**Return parameter object (matches both GET, POST, FILE):**
```php
$object = SimpleRouter::request()->getInput()->getObject('name');
```
**Return specific GET parameter (where name is the name of your parameter):**
```php
$object = SimpleRouter::request()->getInput()->get->name;
$object = SimpleRouter::request()->getInput()->post->name;
$object = SimpleRouter::request()->getInput()->file->name;
```
**Return all parameters:**
```php
// Get all
$objects = SimpleRouter::request()->getInput()->all();
// Only match certain keys
$objects = SimpleRouter::request()->getInput()->all([
'company_name',
'user_id'
]);
```
All object inherits from `InputItem` class and will always contain these methods:
- `getValue()` - returns the value of the input.
- `getIndex()` - returns the index/key of the input.
- `getName()` - returns a human friendly name for the input (company_name will be Company Name etc).
`InputFile` has the same methods as above along with some other file-specific methods like:
- `getTmpName()` - get file temporary name.
- `getSize()` - get file size.
- `move($destination)` - move file to destination.
- `getContents()` - get file content.
- `getType()` - get mime-type for file.
- `getError()` - get file upload error.
### Easy access your input
Create a helper function to easily get access to the input elements.
Example:
```php
/**
* Get input class
* @return \Pecee\Http\Input\Input
*/
function input() {
return SimpleRouter::request()->getInput();
}
```
Then you can easily do something like this in your controller:
```php
// Get parameter site_id or default-value 2
$value = input()->get('site_id', '2');
```
## Sites
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:
-100
View File
@@ -1,100 +0,0 @@
# 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.
@@ -1,22 +0,0 @@
<?php
namespace Demo\Controllers;
use Pecee\SimpleRouter\SimpleRouter;
class ApiController {
public function index() {
// The variable authenticated is set to true in the ApiVerification middleware class.
$request = SimpleRouter::request();
header('content-type: application/json');
echo json_encode([
'authenticated' => $request->authenticated
]);
}
}
@@ -1,29 +0,0 @@
<?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';
}
}
@@ -1,34 +0,0 @@
<?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;
}
}
@@ -1,16 +0,0 @@
<?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;
}
}
@@ -1,13 +0,0 @@
<?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/*'];
}
-27
View File
@@ -1,27 +0,0 @@
<?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) {
// Load our helpers
require_once 'helpers.php';
// Load our custom routes
require_once 'routes.php';
// Do initial stuff
parent::start('\\Demo\\Controllers');
}
}
-31
View File
@@ -1,31 +0,0 @@
<?php
use \Pecee\SimpleRouter\SimpleRouter;
function url($controller, $parameters = null, $getParams = null) {
SimpleRouter::getRoute($controller, $parameters, $getParams);
}
/**
* Get current csrf-token
* @return null|string
*/
function csrf_token() {
$token = new \Pecee\CsrfToken();
return $token->getToken();
}
/**
* Get request object
* @return \Pecee\Http\Request
*/
function request() {
return SimpleRouter::request();
}
/**
* Get response object
* @return \Pecee\Http\Response
*/
function response() {
return SimpleRouter::response();
}
-23
View File
@@ -1,23 +0,0 @@
<?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');
});
});
-26
View File
@@ -1,26 +0,0 @@
{
"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/"
}
}
}
-5
View File
@@ -1,5 +0,0 @@
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1
-7
View File
@@ -1,7 +0,0 @@
<?php
// load composer dependencies
require '../vendor/autoload.php';
// Start the routing
\Demo\Router::start();
-201
View File
@@ -1,201 +0,0 @@
<?php
namespace Pecee\Http\Input;
use Pecee\Http\Request;
class Input {
/**
* @var \Pecee\Http\Input\InputCollection
*/
public $get;
/**
* @var \Pecee\Http\Input\InputCollection
*/
public $post;
/**
* @var \Pecee\Http\Input\InputCollection
*/
public $file;
/**
* @var Request
*/
protected $request;
public function __construct(Request &$request) {
$this->request = $request;
$this->setGet();
$this->setPost();
$this->setFile();
}
/**
* Get all get/post items
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null) {
$output = $this->get->getData();
$output = array_merge($output, $this->post->getData());
if($filter !== null) {
$tmp = array();
foreach($output as $key => $val) {
if(in_array($key, $filter)) {
$tmp[$key] = $val;
}
}
return $tmp;
}
return $output;
}
public function getObject($index, $default = null) {
$key = (strpos($index, '[') > -1) ? substr($index, strpos($index, '[')+1, strpos($index, ']') - strlen($index)) : null;
$index = (strpos($index, '[') > -1) ? substr($index, 0, strpos($index, '[')) : $index;
$element = $this->get->findFirst($index);
if($element !== null) {
return ($key !== null) ? $element[$key] : $element;
}
if($this->request->getMethod() !== 'get') {
$element = $this->post->findFirst($index);
if ($element !== null) {
return ($key !== null) ? $element[$key] : $element;
}
$element = $this->file->findFirst($index);
if ($element !== null) {
return ($key !== null) ? $element[$key] : $element;
}
}
return $default;
}
/**
* Get input element value matching index
* @param string $index
* @param string|null $default
* @return string|null
*/
public function get($index, $default = null) {
$item = $this->getObject($index);
if($item !== null) {
if(is_array($item) || $item instanceof InputFile) {
return $item;
}
return (trim($item->getValue()) === '') ? $default : $item->getValue();
}
return $default;
}
public function exists($index) {
return ($this->getObject($index) !== null);
}
public function setGet() {
$this->get = new InputCollection();
if(count($_GET)) {
foreach($_GET as $key => $get) {
if(!is_array($get)) {
$this->get->{$key} = new InputItem($key, $get);
continue;
}
$output = array();
foreach($get as $k => $g) {
$output[$k] = new InputItem($k, $g);
}
$this->get->{$key} = $output;
}
}
}
public function setPost() {
$this->post = new InputCollection();
$postVars = array();
if(isset($_SERVER['REQUEST_METHOD']) && in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'PATCH', 'DELETE'])) {
parse_str(file_get_contents('php://input'), $postVars);
} else {
$postVars = $_POST;
}
if(count($postVars)) {
foreach($postVars as $key => $post) {
if(!is_array($post)) {
$this->post->{strtolower($key)} = new InputItem($key, $post);
continue;
}
$output = array();
foreach($post as $k=>$p) {
$output[$k] = new InputItem($k, $p);
}
$this->post->{strtolower($key)} = $output;
}
}
}
public function setFile() {
$this->file = new InputCollection();
if(count($_FILES)) {
foreach($_FILES as $key => $value) {
// Multiple files
if(!is_array($value['name'])) {
// Strip empty values
if($value['error'] != '4') {
$file = new InputFile($key);
$file->setName($value['name']);
$file->setSize($value['size']);
$file->setType($value['type']);
$file->setTmpName($value['tmp_name']);
$file->setError($value['error']);
$this->file->{strtolower($key)} = $file;
}
continue;
}
$output = array();
foreach($value['name'] as $k=>$val) {
// Strip empty values
if($value['error'][$k] != '4') {
$file = new InputFile($k);
$file->setName($value['name'][$k]);
$file->setSize($value['size'][$k]);
$file->setType($value['type'][$k]);
$file->setTmpName($value['tmp_name'][$k]);
$file->setError($value['error'][$k]);
$output[$k] = $file;
}
}
$this->file->{strtolower($key)} = $output;
}
}
}
}
-67
View File
@@ -1,67 +0,0 @@
<?php
namespace Pecee\Http\Input;
class InputCollection implements \IteratorAggregate {
protected $data = array();
/**
* Search for input element matching index.
* Useful for searching for finding items where $index doesn't contain form name.
*
* @param string $index
* @return mixed
*/
public function findFirst($index) {
if(count($this->data)) {
if(isset($this->data[$index])) {
return $this->data[$index];
}
foreach($this->data as $key => $value) {
if(strtolower($index) === strtolower($key)) {
return $value;
}
}
}
return null;
}
/**
* @param $index
* @throws \InvalidArgumentException
* @return InputItem
*/
public function __get($index) {
$item = $this->findFirst($index);
// Ensure that item are always available
if($item === null) {
$this->data[$index] = new InputItem($index, null);
return $this->data[$index];
}
return $item;
}
public function __set($index, $value) {
$this->data[$index] = $value;
}
public function getData() {
return $this->data;
}
/**
* Retrieve an external iterator
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return \Traversable An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
* @since 5.0.0
*/
public function getIterator() {
return new \ArrayIterator($this->data);
}
}
-68
View File
@@ -1,68 +0,0 @@
<?php
namespace Pecee\Http\Input;
class InputFile extends InputItem {
protected $name;
protected $size;
protected $type;
protected $error;
protected $tmpName;
/**
* @return string
*/
public function getSize() {
return $this->size;
}
/**
* @return string
*/
public function getType() {
return $this->type;
}
/**
* @return string
*/
public function getError() {
return $this->error;
}
/**
* @return string
*/
public function getTmpName() {
return $this->tmpName;
}
public function getExtension() {
return pathinfo($this->getName(), PATHINFO_EXTENSION);
}
public function move($destination) {
return move_uploaded_file($this->tmpName, $destination);
}
public function getContents() {
return file_get_contents($this->tmpName);
}
public function setTmpName($name) {
$this->tmpName = $name;
}
public function setSize($size) {
$this->size = $size;
}
public function setType($type) {
$this->type = $type;
}
public function setError($error) {
$this->error = $error;
}
}
-63
View File
@@ -1,63 +0,0 @@
<?php
namespace Pecee\Http\Input;
class InputItem {
protected $index;
protected $name;
protected $value;
public function __construct($index, $value = null) {
$this->index = $index;
$this->value = $value;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
/**
* @return array
*/
public function getName() {
return $this->name;
}
/**
* @return array
*/
public function getValue() {
return $this->value;
}
/**
* @return string
*/
public function getIndex() {
return $this->index;
}
/**
* Set input name
* @param string $name
* @return static $this
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Set input value
* @param string $value
* @return static $this
*/
public function setValue($value) {
$this->value = $value;
return $this;
}
public function __toString() {
return (string)$this->getValue();
}
}
+23 -14
View File
@@ -1,19 +1,29 @@
<?php
namespace Pecee\Http;
use Pecee\Http\Input\Input;
class Request {
protected static $instance;
protected $data;
/**
* Return new instance
* @return static
*/
public static function getInstance() {
if(self::$instance === null) {
self::$instance = new static();
}
return self::$instance;
}
public function __construct() {
$this->data = array();
$this->host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : array();
$this->uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : array();
$this->method = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : (isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : array());
$this->host = $_SERVER['HTTP_HOST'];
$this->uri = $_SERVER['REQUEST_URI'];
$this->method = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
$this->headers = $this->getAllHeaders();
$this->input = new Input($this);
}
protected function getAllHeaders() {
@@ -83,10 +93,7 @@ class Request {
* @return string
*/
public function getIp() {
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);
return isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
}
/**
@@ -115,11 +122,13 @@ class Request {
}
/**
* Get input class
* @return Input
* Get request input or default value
* @param string $name
* @param string $defaultValue
* @return mixed
*/
public function getInput() {
return $this->input;
public function getInput($name, $defaultValue) {
return (isset($_REQUEST[$name]) ? $_REQUEST[$name] : $defaultValue);
}
public function isFormatAccepted($format) {
+1 -7
View File
@@ -4,12 +4,6 @@ namespace Pecee\Http;
class Response {
protected $request;
public function __construct(Request &$request) {
$this->request = $request;
}
/**
* Set the http status code
*
@@ -37,7 +31,7 @@ class Response {
}
public function refresh() {
$this->redirect($this->request->getUri());
$this->redirect(Request::getInstance()->getUri());
}
/**
+99 -137
View File
@@ -5,14 +5,12 @@ use Pecee\Exception\RouterException;
use Pecee\Handler\IExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response;
class RouterBase {
protected static $instance;
protected $request;
protected $response;
protected $currentRoute;
protected $routes;
protected $processedRoutes;
@@ -21,20 +19,15 @@ class RouterBase {
protected $defaultNamespace;
protected $bootManagers;
protected $baseCsrfVerifier;
protected $exceptionHandlers;
// TODO: clean up - cut some of the methods down to smaller pieces
public function __construct() {
$this->reset();
}
public function reset() {
$this->request = new Request();
$this->response = new Response($this->request);
$this->routes = array();
$this->backStack = array();
$this->controllerUrlMap = array();
$this->request = Request::getInstance();
$this->bootManagers = array();
$this->exceptionHandlers = array();
}
public function addRoute(RouterEntry $route) {
@@ -63,9 +56,11 @@ class RouterBase {
}
if($this->defaultNamespace && !$route->getNamespace()) {
$namespace = $this->defaultNamespace;
$namespace = null;
if ($route->getNamespace()) {
$namespace .= '\\' . $route->getNamespace();
$namespace = $this->defaultNamespace . '\\' . $route->getNamespace();
} else {
$namespace = $this->defaultNamespace;
}
$route->setNamespace($namespace);
@@ -77,36 +72,27 @@ class RouterBase {
array_push($newPrefixes, trim($route->getPrefix(), '/'));
}
/* @var $group RouterGroup */
$group = null;
if(!($route instanceof RouterGroup)) {
if(is_array($newPrefixes) && count($newPrefixes) && $backStack) {
$route->setUrl( '/' . join('/', $newPrefixes) . $route->getUrl() );
}
$group = null;
$this->controllerUrlMap[] = $route;
}
$this->currentRoute = $route;
if($route instanceof RouterGroup && is_callable($route->getCallback())) {
$group = $route;
$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;
}
// Load middleware on group if route matches
if($route->getPrefix() !== null && $route->matchRoute($this->request)) {
$route->loadMiddleware($this->request);
}
$route->renderRoute($this->request);
$mergedSettings = array_merge($settings, $route->getMergeableSettings());
}
$this->currentRoute = null;
@@ -121,68 +107,72 @@ class RouterBase {
}
}
public function routeRequest($original = true) {
public function routeRequest() {
$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;
try {
// 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.');
}
}
// Make sure routes with longer urls are rendered first
usort($this->controllerUrlMap, function($a, $b) {
if(strlen($a->getUrl()) < strlen($b->getUrl())) {
return 1;
}
return -1;
});
// Loop through each route-request
$this->processRoutes($this->routes);
$max = count($this->controllerUrlMap);
if($original === true) {
// Verify csrf token for request
if ($this->baseCsrfVerifier !== null) {
$this->baseCsrfVerifier->handle($this->request);
/* @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;
}
}
$max = count($this->controllerUrlMap);
$routeNotAllowed = false;
/* @var $route RouterEntry */
for ($i = 0; $i < $max; $i++) {
$this->request->rewrite_uri = $this->request->uri;
$this->request->setUri($originalUri);
$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 = $route;
$route->loadMiddleware($this->request);
try {
$this->request->loadedRoute->renderRoute($this->request);
break;
} catch(\Exception $e) {
$this->handleException($e);
}
}
} catch(\Exception $e) {
$this->handleException($e);
break;
}
}
if($routeNotAllowed) {
@@ -190,31 +180,18 @@ class RouterBase {
}
if(!$this->request->loadedRoute) {
$this->handleException(new RouterException(sprintf('Route not found: %s', $this->request->getUri()), 404));
throw new RouterException(sprintf('Route not found: %s', $this->request->getUri()), 404);
}
}
protected function handleException(\Exception $e) {
$request = null;
/* @var $route RouterGroup */
foreach ($this->exceptionHandlers as $route) {
$route->loadMiddleware($this->request);
$handler = $route->getExceptionHandler();
$handler = new $handler();
if (!($handler instanceof IExceptionHandler)) {
if($this->request->loadedRoute !== null && $this->request->loadedRoute->exceptionHandler !== null) {
$handler = new $this->request->loadedRoute->exceptionHandler();
if(!($handler instanceof IExceptionHandler)) {
throw new RouterException('Exception handler must implement the IExceptionHandler interface.');
}
$request = $handler->handleError($this->request, $this->request->loadedRoute, $e);
}
if($request !== null) {
$this->request = $request;
$this->routeRequest(false);
return;
$handler->handleError($this->request, $this->request->loadedRoute, $e);
}
throw $e;
@@ -229,11 +206,9 @@ class RouterBase {
/**
* @param string $defaultNamespace
* @return static
*/
public function setDefaultNamespace($defaultNamespace) {
$this->defaultNamespace = $defaultNamespace;
return $this;
}
/**
@@ -294,14 +269,6 @@ class RouterBase {
return $this->request;
}
/**
* Get response
* @return Response
*/
public function getResponse() {
return $this->response;
}
/**
* Get base csrf verifier class
* @return BaseCsrfVerifier
@@ -322,21 +289,18 @@ class RouterBase {
}
public function arrayToParams(array $getParams = null, $includeEmpty = true) {
if(is_array($getParams) && count($getParams)) {
if ($includeEmpty === false) {
$getParams = array_filter($getParams, function ($item) {
return (!empty($item));
});
if (is_array($getParams) && count($getParams) > 0) {
foreach ($getParams as $key => $val) {
if (!empty($val) || empty($val) && $includeEmpty) {
$getParams[$key] = $key . '=' . $val;
}
}
return '?' . http_build_query($getParams);
return join('&', $getParams);
}
return '';
}
protected function processUrl(RouterRoute $route, $method = null, $parameters = null, $getParams = null) {
protected function processUrl($route, $method = null, $parameters = null, $getParams = null) {
$domain = '';
@@ -354,10 +318,10 @@ class RouterBase {
$url = $domain . '/' . trim($route->getUrl(), '/');
if(($route instanceof RouterController || $route instanceof RouterResource) && $method !== null) {
if($method !== null) {
$url .= $method;
}
$url .= $method;
}
if($route instanceof RouterController || $route instanceof RouterResource) {
if(count($parameters)) {
$url .= join('/', $parameters);
}
@@ -387,8 +351,8 @@ class RouterBase {
$url = rtrim($url, '/') . '/';
if($getParams !== null) {
$url .= $this->arrayToParams($getParams);
if($getParams !== null && count($getParams)) {
$url .= '?' . $this->arrayToParams($getParams);
}
return $url;
@@ -408,10 +372,11 @@ class RouterBase {
if($controller === null && $parameters === null) {
$getParams = (is_array($getParams)) ? array_merge($_GET, $getParams) : $_GET;
$url = parse_url($this->request->getUri(), PHP_URL_PATH);
$url = parse_url(Request::getInstance()->getUri());
$url = $url['path'];
if($getParams !== null) {
$url .= $this->arrayToParams($getParams);
if(count($getParams)) {
$url .= '?' . $this->arrayToParams($getParams);
}
return $url;
@@ -432,15 +397,12 @@ class RouterBase {
$route = $this->controllerUrlMap[$i];
// Check an alias exist, if the matches - use it
if($route instanceof RouterRoute) {
if($route instanceof RouterRoute && $route->hasAlias($controller)) {
return $this->processUrl($route, $route->getMethod(), $parameters, $getParams);
}
if($route->hasAlias($controller)) {
return $this->processUrl($route, $route->getMethod(), $parameters, $getParams);
}
if(!is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) {
$c = $route->getCallback();
}
if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) {
$c = $route->getCallback();
} else if($route instanceof RouterController || $route instanceof RouterResource) {
$c = $route->getController();
}
@@ -485,22 +447,22 @@ class RouterBase {
$url = '/' . trim(join('/', $url), '/') . '/';
if($getParams !== null) {
$url .= $this->arrayToParams($getParams);
if($getParams !== null && count($getParams)) {
$url .= '?' . $this->arrayToParams($getParams);
}
return $url;
}
/**
* Get current router instance
* @return static
*/
public static function getInstance() {
if(static::$instance === null) {
static::$instance = new static();
if(self::$instance === null) {
self::$instance = new static();
}
return static::$instance;
return self::$instance;
}
public static function reset() {
self::$instance = null;
}
}
+13 -8
View File
@@ -232,7 +232,7 @@ abstract class RouterEntry {
}
/**
* Dynamically set settings value
* Dynamicially set settings value
*
* @param string $name
* @param mixed|null $value
@@ -249,7 +249,7 @@ abstract class RouterEntry {
return new $name();
}
protected function parseParameters($route, $url, $parameterRegex = '[\w]+') {
protected function parseParameters($route, $url, $parameterRegex = '[a-z0-9]+') {
$parameterNames = array();
$regex = '';
$lastCharacter = '';
@@ -261,6 +261,12 @@ abstract class RouterEntry {
$character = $route[$i];
// Skip "/" if we are at the end of a parameter
if($lastCharacter === '}' && $character === '/') {
$lastCharacter = $character;
continue;
}
if($character === '{') {
// Remove "/" and "\" from regex
if(substr($regex, strlen($regex)-1) === '/') {
@@ -279,10 +285,10 @@ abstract class RouterEntry {
if($lastCharacter === '?') {
$parameter = substr($parameter, 0, strlen($parameter)-1);
$regex .= '(?:\/?(?P<' . $parameter . '>'. $parameterRegex .')[^\/]?)?';
$regex .= '(?:\\/?(?P<'.$parameter.'>[^\/]+)?\\/?)';
$required = false;
} else {
$regex .= '\/?(?P<' . $parameter . '>'. $parameterRegex .')[^\/]?';
$regex .= '\\/(?P<' . $parameter . '>'. $parameterRegex .')\\/';
}
$parameterNames[] = array('name' => $parameter, 'required' => $required);
$parameter = '';
@@ -301,8 +307,7 @@ abstract class RouterEntry {
$parameterValues = array();
if(preg_match('/^'.$regex.'\/?$/is', $url, $parameterValues)) {
if(preg_match('/^'.$regex.'$/is', $url, $parameterValues)) {
$parameters = array();
$max = count($parameterNames);
@@ -310,7 +315,7 @@ abstract class RouterEntry {
if($max) {
for($i = 0; $i < $max; $i++) {
$name = $parameterNames[$i];
$parameterValue = isset($parameterValues[$name['name']]) ? $parameterValues[$name['name']] : null;
$parameterValue = (isset($parameterValues[$name['name']]) && !empty($parameterValues[$name['name']])) ? $parameterValues[$name['name']] : null;
if($name['required'] && $parameterValue === null) {
throw new RouterException('Missing required parameter ' . $name['name'], 404);
@@ -394,7 +399,7 @@ abstract class RouterEntry {
}
/**
* Get allowed request methods
* Get allowed requeset methods
*
* @return array
*/
-15
View File
@@ -92,24 +92,9 @@ class RouterGroup extends RouterEntry {
if($this->getNamespace() !== null && isset($settings['namespace'])) {
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;
}
+1 -1
View File
@@ -52,7 +52,7 @@ class RouterResource extends RouterEntry {
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
$parameters = $this->parseParameters($route, $url);
$parameters = $this->parseParameters($route, $url, '[0-9]+?');
if($parameters !== null) {
+3 -1
View File
@@ -103,7 +103,9 @@ class RouterRoute extends RouterEntry {
}
}
} else {
return strtolower($this->getAlias()) === strtolower($name);
if(strtolower($this->getAlias()) === strtolower($name)) {
return true;
}
}
return false;
+49 -41
View File
@@ -13,17 +13,15 @@ use Pecee\Http\Middleware\BaseCsrfVerifier;
class SimpleRouter {
public function __construct() {
die('test');
}
/**
* Start/route request
* @param null $defaultNamespace
* @throws \Pecee\Exception\RouterException
*/
public static function start($defaultNamespace = null) {
RouterBase::getInstance()->setDefaultNamespace($defaultNamespace)->routeRequest();
$router = RouterBase::getInstance();
$router->setDefaultNamespace($defaultNamespace);
$router->routeRequest();
}
/**
@@ -39,19 +37,47 @@ class SimpleRouter {
}
public static function get($url, $callback, array $settings = null) {
return self::match(['get'], $url, $callback, $settings);
$route = new RouterRoute($url, $callback);
$route->addSettings($settings);
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_GET));
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function post($url, $callback, array $settings = null) {
return self::match(['post'], $url, $callback, $settings);
$route = new RouterRoute($url, $callback);
$route->addSettings($settings);
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_POST));
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function put($url, $callback, array $settings = null) {
return self::match(['put'], $url, $callback, $settings);
$route = new RouterRoute($url, $callback);
$route->addSettings($settings);
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_PUT, RouterRoute::REQUEST_TYPE_PATCH));
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function delete($url, $callback, array $settings = null) {
return self::match(['delete'], $url, $callback, $settings);
$route = new RouterRoute($url, $callback);
$route->addSettings($settings);
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_DELETE));
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function group($settings = array(), $callback) {
@@ -62,7 +88,8 @@ class SimpleRouter {
$group->setSettings($settings);
}
RouterBase::getInstance()->addRoute($group);
$router = RouterBase::getInstance();
$router->addRoute($group);
return $group;
}
@@ -82,48 +109,37 @@ class SimpleRouter {
public static function match(array $requestMethods, $url, $callback, array $settings = null) {
$route = new RouterRoute($url, $callback);
$route->setRequestMethods($requestMethods);
$route->addSettings($settings);
if($settings !== null) {
$route->addSettings($settings);
}
RouterBase::getInstance()->addRoute($route);
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function all($url, $callback, array $settings = null) {
$route = new RouterRoute($url, $callback);
if($settings !== null) {
$route->addSettings($settings);
}
RouterBase::getInstance()->addRoute($route);
$route->addSettings($settings);
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function controller($url, $controller, array $settings = null) {
$route = new RouterController($url, $controller);
if($settings !== null) {
$route->addSettings($settings);
}
RouterBase::getInstance()->addRoute($route);
$route->addSettings($settings);
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
public static function resource($url, $controller, array $settings = null) {
$route = new RouterResource($url, $controller);
if($settings !== null) {
$route->addSettings($settings);
}
RouterBase::getInstance()->addRoute($route);
$route->addSettings($settings);
$router = RouterBase::getInstance();
$router->addRoute($route);
return $route;
}
@@ -132,12 +148,4 @@ class SimpleRouter {
return RouterBase::getInstance()->getRoute($controller, $parameters, $getParams);
}
public static function request() {
return RouterBase::getInstance()->getRequest();
}
public static function response() {
return RouterBase::getInstance()->getResponse();
}
}
-9
View File
@@ -6,13 +6,4 @@ class DummyController {
echo static::class . '@' .'start() OK';
}
public function param($params = null) {
$params = func_get_args();
echo 'Params: ' . join(', ', $params);
}
public function notFound() {
echo 'not found';
}
}
-8
View File
@@ -1,8 +0,0 @@
<?php
class ExceptionHandler implements \Pecee\Handler\IExceptionHandler {
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\RouterEntry $router = null, \Exception $error){
throw $error;
}
}
+10 -3
View File
@@ -7,11 +7,19 @@ 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;
@@ -27,10 +35,9 @@ class GroupTest extends PHPUnit_Framework_TestCase {
}
public function testNestedGroup() {
\Pecee\SimpleRouter\RouterBase::reset();
\Pecee\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/api/v1/test');
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\Http\Request::getInstance()->setUri('/api/v1/test');
\Pecee\SimpleRouter\SimpleRouter::group(['prefix' => '/api'], function() {
\Pecee\SimpleRouter\SimpleRouter::group(['prefix' => '/v1'], function() {
+16 -11
View File
@@ -2,30 +2,35 @@
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\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/my/test/url');
\Pecee\Http\Request::getInstance()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function() {
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
});
\Pecee\SimpleRouter\RouterBase::reset();
$found = false;
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
try {
\Pecee\SimpleRouter\SimpleRouter::start();
}catch(\Exception $e) {
$found = ($e instanceof MiddlewareLoadedException);
}catch(Exception $e) {
$this->assertTrue(($e instanceof MiddlewareLoadedException));
return;
}
$this->assertTrue($found);
throw new Exception('Middleware not loaded');
}
}
+22 -69
View File
@@ -2,63 +2,48 @@
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\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::request()->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::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/my/test/url');
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\SimpleRouter\RouterBase::reset();
\Pecee\Http\Request::getInstance()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start');
\Pecee\SimpleRouter\SimpleRouter::start();
}
public function testPost() {
\Pecee\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/my/test/url');
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('post');
\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()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/my/test/url');
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('put');
\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()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/my/test/url');
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('delete');
\Pecee\Http\Request::getInstance()->setMethod('delete');
\Pecee\SimpleRouter\RouterBase::reset();
\Pecee\SimpleRouter\SimpleRouter::delete('/my/test/url', 'DummyController@start');
\Pecee\SimpleRouter\SimpleRouter::start();
@@ -66,9 +51,10 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase {
}
public function testMethodNotAllowed() {
\Pecee\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/my/test/url');
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('post');
\Pecee\SimpleRouter\RouterBase::reset();
\Pecee\Http\Request::getInstance()->setMethod('post');
\Pecee\SimpleRouter\SimpleRouter::get('/my/test/url', 'DummyController@start');
@@ -80,37 +66,4 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase {
}
public function testSimpleParam() {
\Pecee\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/test-param1');
\Pecee\SimpleRouter\SimpleRouter::get('/test-{param1}', 'DummyController@param');
\Pecee\SimpleRouter\SimpleRouter::start();
}
public function testMultiParam() {
\Pecee\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/test-param1-param2');
\Pecee\SimpleRouter\SimpleRouter::get('/test-{param1}-{param2}', 'DummyController@param');
\Pecee\SimpleRouter\SimpleRouter::start();
}
public function testPathParamRegex() {
\Pecee\SimpleRouter\RouterBase::getInstance()->reset();
\Pecee\SimpleRouter\SimpleRouter::request()->setMethod('get');
\Pecee\SimpleRouter\SimpleRouter::request()->setUri('/test/path/123123');
\Pecee\SimpleRouter\SimpleRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
\Pecee\SimpleRouter\SimpleRouter::start();
}
}