Initial commit

This commit is contained in:
Porawit Dongwang
2026-09-16 23:20:08 +07:00
commit 0041668dbb
32577 changed files with 3687927 additions and 0 deletions
@@ -0,0 +1,28 @@
name: CI
on:
push:
pull_request:
jobs:
tests:
name: Tests on PHP ${{ matrix.php }} ${{ matrix.dependencies }}
runs-on: ubuntu-20.04
container:
image: shivammathur/node:2004
strategy:
matrix:
php: ['5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
dependencies: ['', '--prefer-lowest --prefer-stable']
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
- uses: shivammathur/setup-php@2.9.0
with:
php-version: ${{ matrix.php }}
- name: Install dependencies
run: composer update --no-interaction --prefer-dist ${{ matrix.dependencies }}
- name: Configure PHPUnit problem matchers
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Run tests
run: ./vendor/bin/phpunit
@@ -0,0 +1,6 @@
.DS_Store
/composer.lock
/vendor/
tests-report/
/.idea/
.php_cs.cache
@@ -0,0 +1,57 @@
<?php
/**
* @source https://gist.github.com/codfish/c77d348820c1c6b4ebe4a66dc2291c74
*
* Rules we follow are from PSR-2 as well as the rectified PSR-2 guide.
*
* - https://github.com/FriendsOfPHP/PHP-CS-Fixer
* - https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
* - https://github.com/php-fig-rectified/fig-rectified-standards/blob/master/PSR-2-R-coding-style-guide-additions.md
*
* If something isn't addressed in either of those, some other common community rules are
* used that might not be addressed explicitly in PSR-2 in order to improve code quality
* (so that devs don't need to comment on them in Code Reviews).
*
* For instance: removing trailing white space, removing extra line breaks where
* they're not needed (back to back, beginning or end of function/class, etc.),
* adding trailing commas in the last line of an array, etc.
*/
$finder = PhpCsFixer\Finder::create()
->exclude('node_modules')
->exclude('vendor')
->in(__DIR__);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => [ 'syntax' => 'long' ],
'binary_operator_spaces' => [ 'align_equals' => false, 'align_double_arrow' => false ],
'cast_spaces' => true,
'combine_consecutive_unsets' => true,
'concat_space' => [ 'spacing' => 'one' ],
'linebreak_after_opening_tag' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_extra_consecutive_blank_lines' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_whitespace_in_blank_line' => true,
'no_spaces_around_offset' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'normalize_index_brace' => true,
'phpdoc_indent' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'single_quote' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'method_argument_space' => ['ensure_fully_multiline' => false],
'no_break_comment' => false,
'blank_line_before_statement' => true,
])
->setFinder($finder);
@@ -0,0 +1,89 @@
# Changelog for `bramus/router`
## 1.next ????.??.??
## 1.6.1 2021.11.19
- Fixed: Fix `trigger404()` to work without custom 404 handler _([#169](https://github.com/bramus/router/pull/169))_ _(@mjoris)_
## 1.6 2021.07.23
- Added: Ability to set multiple 404s, depending on the route prefix _(@uvulpos)_
## 1.5 2020.10.26
- Fixed: Correctly invoke static/non-static class methods _(@bramus)_
- Fixed: Fix PHP 5.3 support _(@cikal)_
- Fixed: Fix arguments in demo _(@khromov)_
- Fixed: Fix #72 _(@acicali)_
- Added: PHP 7.4 support _(@ShaneMcC)_
- Added: Ability to externally trigger a 404 _(@PlanetTheCloud)_
## 1.4.2 2019.02.27
- Fixed: Play nice with emoji in base paths ([ref](https://github.com/bramus/router/commit/8692190532db269882f83d27cea95d4f22a50da2#commitcomment-32492636), [ref](https://github.com/bramus/router/commit/492444d84fde7e54551ff0bf8ca79ff9292094da#commitcomment-32496820)) _(@bramus)_
- Added: Extra Tests _(@bramus)_
## 1.4.1 2019.02.26
- Fixed: Fix bug where Cyrillic charges and Emojis in placeholder were urlencoded (see [#80](https://github.com/bramus/router/issues/80#issuecomment-467154490)) _(@bramus)_
- Fixed: Make `bramus/router` play nice with situations where the entry script and entry URLs are not coupled (see [#82](https://github.com/bramus/router/issues/82#issuecomment-466956078)) _(@bramus)_
- Changed: Changed visibility of `getBasePath` and `getCurrentUri` to being `public` _(@bramus)_
## 1.4 2019.02.18
- Added: Support for Cyrillic chars and Emoji in placeholder values and placeholder names (see [#80](https://github.com/bramus/router/issues/80)) _(@bramus)_
- Added: `composer test` shorthand _(@bramus)_
- Added: Changelog _(@bramus)_
- Changed: Documentation Improvements _(@bramus)_
## 1.3.1 2017.12.22
- Added: Extra Tests _(@bramus)_
- Changed: Documentation Improvements _(@artyuum)_
## 1.3 2017.12.21
- Added: Support `Class@method` callbacks in `set404()` _(@bramus)_
- Changed: Refactored callback invocation _(@bramus)_
- Changed: Documentation Improvements _(@artyuum)_
## 1.2.1 2017.10.06
- Changed: Documentation Improvements _(@bramus)_
## 1.2 2017.10.06
- Added: Support route matching using _“placeholders”_ (e.g. curly braces) _(@ovflowd)_
- Added: Default Namespace Capability using `setNamespace()`, for use with `Class@Method` calls _(@ovflowd)_
- Added: Extra Tests _(@bramus)_
- Bugfix: Make sure callable are actually callable _(@ovflowd)_
- Demo: Added a multilang demo _(@bramus)_
- Changed: Documentation Improvements _(@lai0n)_
## 1.1 2016.05.26
- Added: Return `true` if a route was handled, `false` otherwise _(@tleb)_
- Added: `getBasePath()` _(@ovflowd)_
- Added: Support `Class@Method` calls _(@ovflowd)_
- Changed: Tweak a few method signaturs so that they're protected _(@tleb)_
- Changed: Documentation Improvements _(@tleb)_
## 1.0 2015.02.04
- First 1.x release
## _(Unversioned Releases)_ 2013.04.08 - 2015.02.04
- Initial release with suppport for:
- Static and Dynamic Route Handling
- Shorthands: `get()`, `post()`, `put()`, `delete()`, and `options()`
- Before Route Middlewares / Before Route Middlewares: `before()`
- After Router Middlewares / Run Callback
- Added: Optional Route Patterns
- Added: Subrouting (mount callables onto a subroute/prefix)
- Added: `patch()` shorthand
- Added: Support for `X-HTTP-Method-Override` header
- Bugfix: Use the HTTP version as found in `['SERVER_PROTOCOL']`
- Bugfix: Nested Subpatterns / Multiple Matching _(@jbleuzen)_
@@ -0,0 +1,19 @@
Copyright (c) 2013 Bram(us) Van Damme - http://www.bram.us/
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,472 @@
# bramus/router
[![Build Status](https://github.com/bramus/router/workflows/CI/badge.svg)](https://github.com/bramus/router/actions) [![Source](http://img.shields.io/badge/source-bramus/router-blue.svg?style=flat-square)](https://github.com/bramus/router) [![Version](https://img.shields.io/packagist/v/bramus/router.svg?style=flat-square)](https://packagist.org/packages/bramus/router) [![Downloads](https://img.shields.io/packagist/dt/bramus/router.svg?style=flat-square)](https://packagist.org/packages/bramus/router/stats) [![License](https://img.shields.io/packagist/l/bramus/router.svg?style=flat-square)](https://github.com/bramus/router/blob/master/LICENSE)
A lightweight and simple object oriented PHP Router.
Built by Bram(us) Van Damme _([https://www.bram.us](https://www.bram.us))_ and [Contributors](https://github.com/bramus/router/graphs/contributors)
## Features
- Supports `GET`, `POST`, `PUT`, `DELETE`, `OPTIONS`, `PATCH` and `HEAD` request methods
- [Routing shorthands such as `get()`, `post()`, `put()`, …](#routing-shorthands)
- [Static Route Patterns](#route-patterns)
- Dynamic Route Patterns: [Dynamic PCRE-based Route Patterns](#dynamic-pcre-based-route-patterns) or [Dynamic Placeholder-based Route Patterns](#dynamic-placeholder-based-route-patterns)
- [Optional Route Subpatterns](#optional-route-subpatterns)
- [Supports `X-HTTP-Method-Override` header](#overriding-the-request-method)
- [Subrouting / Mounting Routes](#subrouting--mounting-routes)
- [Allowance of `Class@Method` calls](#classmethod-calls)
- [Custom 404 handling](#custom-404)
- [Before Route Middlewares](#before-route-middlewares)
- [Before Router Middlewares / Before App Middlewares](#before-router-middlewares)
- [After Router Middleware / After App Middleware (Finish Callback)](#after-router-middleware--run-callback)
- [Works fine in subfolders](#subfolder-support)
## Prerequisites/Requirements
- PHP 5.3 or greater
- [URL Rewriting](https://gist.github.com/bramus/5332525)
## Installation
Installation is possible using Composer
```
composer require bramus/router ~1.6
```
## Demo
A demo is included in the `demo` subfolder. Serve it using your favorite web server, or using PHP 5.4+'s built-in server by executing `php -S localhost:8080` on the shell. A `.htaccess` for use with Apache is included.
Additionally a demo of a mutilingual router is also included. This can be found in the `demo-multilang` subfolder and can be ran in the same manner as the normal demo.
## Usage
Create an instance of `\Bramus\Router\Router`, define some routes onto it, and run it.
```php
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Create Router instance
$router = new \Bramus\Router\Router();
// Define routes
// ...
// Run it!
$router->run();
```
### Routing
Hook __routes__ (a combination of one or more HTTP methods and a pattern) using `$router->match(method(s), pattern, function)`:
```php
$router->match('GET|POST', 'pattern', function() { });
```
`bramus/router` supports `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` _(see [note](#a-note-on-making-head-requests))_, and `OPTIONS` HTTP request methods. Pass in a single request method, or multiple request methods separated by `|`.
When a route matches against the current URL (e.g. `$_SERVER['REQUEST_URI']`), the attached __route handling function__ will be executed. The route handling function must be a [callable](http://php.net/manual/en/language.types.callable.php). Only the first route matched will be handled. When no matching route is found, a 404 handler will be executed.
### Routing Shorthands
Shorthands for single request methods are provided:
```php
$router->get('pattern', function() { /* ... */ });
$router->post('pattern', function() { /* ... */ });
$router->put('pattern', function() { /* ... */ });
$router->delete('pattern', function() { /* ... */ });
$router->options('pattern', function() { /* ... */ });
$router->patch('pattern', function() { /* ... */ });
```
You can use this shorthand for a route that can be accessed using any method:
```php
$router->all('pattern', function() { });
```
Note: Routes must be hooked before `$router->run();` is being called.
Note: There is no shorthand for `match()` as `bramus/router` will internally re-route such requrests to their equivalent `GET` request, in order to comply with RFC2616 _(see [note](#a-note-on-making-head-requests))_.
### Route Patterns
Route Patterns can be static or dynamic:
- __Static Route Patterns__ contain no dynamic parts and must match exactly against the `path` part of the current URL.
- __Dynamic Route Patterns__ contain dynamic parts that can vary per request. The varying parts are named __subpatterns__ and are defined using either Perl-compatible regular expressions (PCRE) or by using __placeholders__
#### Static Route Patterns
A static route pattern is a regular string representing a URI. It will be compared directly against the `path` part of the current URL.
Examples:
- `/about`
- `/contact`
Usage Examples:
```php
// This route handling function will only be executed when visiting http(s)://www.example.org/about
$router->get('/about', function() {
echo 'About Page Contents';
});
```
#### Dynamic PCRE-based Route Patterns
This type of Route Patterns contain dynamic parts which can vary per request. The varying parts are named __subpatterns__ and are defined using regular expressions.
Examples:
- `/movies/(\d+)`
- `/profile/(\w+)`
Commonly used PCRE-based subpatterns within Dynamic Route Patterns are:
- `\d+` = One or more digits (0-9)
- `\w+` = One or more word characters (a-z 0-9 _)
- `[a-z0-9_-]+` = One or more word characters (a-z 0-9 _) and the dash (-)
- `.*` = Any character (including `/`), zero or more
- `[^/]+` = Any character but `/`, one or more
Note: The [PHP PCRE Cheat Sheet](https://courses.cs.washington.edu/courses/cse154/15sp/cheat-sheets/php-regex-cheat-sheet.pdf) might come in handy.
The __subpatterns__ defined in Dynamic PCRE-based Route Patterns are converted to parameters which are passed into the route handling function. Prerequisite is that these subpatterns need to be defined as __parenthesized subpatterns__, which means that they should be wrapped between parens:
```php
// Bad
$router->get('/hello/\w+', function($name) {
echo 'Hello ' . htmlentities($name);
});
// Good
$router->get('/hello/(\w+)', function($name) {
echo 'Hello ' . htmlentities($name);
});
```
Note: The leading `/` at the very beginning of a route pattern is not mandatory, but is recommended.
When multiple subpatterns are defined, the resulting __route handling parameters__ are passed into the route handling function in the order they are defined in:
```php
$router->get('/movies/(\d+)/photos/(\d+)', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
#### Dynamic Placeholder-based Route Patterns
This type of Route Patterns are the same as __Dynamic PCRE-based Route Patterns__, but with one difference: they don't use regexes to do the pattern matching but they use the more easy __placeholders__ instead. Placeholders are strings surrounded by curly braces, e.g. `{name}`. You don't need to add parens around placeholders.
Examples:
- `/movies/{id}`
- `/profile/{username}`
Placeholders are easier to use than PRCEs, but offer you less control as they internally get translated to a PRCE that matches any character (`.*`).
```php
$router->get('/movies/{movieId}/photos/{photoId}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
Note: the name of the placeholder does not need to match with the name of the parameter that is passed into the route handling function:
```php
$router->get('/movies/{foo}/photos/{bar}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
### Optional Route Subpatterns
Route subpatterns can be made optional by making the subpatterns optional by adding a `?` after them. Think of blog URLs in the form of `/blog(/year)(/month)(/day)(/slug)`:
```php
$router->get(
'/blog(/\d+)?(/\d+)?(/\d+)?(/[a-z0-9_-]+)?',
function($year = null, $month = null, $day = null, $slug = null) {
if (!$year) { echo 'Blog overview'; return; }
if (!$month) { echo 'Blog year overview'; return; }
if (!$day) { echo 'Blog month overview'; return; }
if (!$slug) { echo 'Blog day overview'; return; }
echo 'Blogpost ' . htmlentities($slug) . ' detail';
}
);
```
The code snippet above responds to the URLs `/blog`, `/blog/year`, `/blog/year/month`, `/blog/year/month/day`, and `/blog/year/month/day/slug`.
Note: With optional parameters it is important that the leading `/` of the subpatterns is put inside the subpattern itself. Don't forget to set default values for the optional parameters.
The code snipped above unfortunately also responds to URLs like `/blog/foo` and states that the overview needs to be shown - which is incorrect. Optional subpatterns can be made successive by extending the parenthesized subpatterns so that they contain the other optional subpatterns: The pattern should resemble `/blog(/year(/month(/day(/slug))))` instead of the previous `/blog(/year)(/month)(/day)(/slug)`:
```php
$router->get('/blog(/\d+(/\d+(/\d+(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
```
Note: It is highly recommended to __always__ define successive optional parameters.
To make things complete use [quantifiers](http://www.php.net/manual/en/regexp.reference.repetition.php) to require the correct amount of numbers in the URL:
```php
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
```
### Subrouting / Mounting Routes
Use `$router->mount($baseroute, $fn)` to mount a collection of routes onto a subroute pattern. The subroute pattern is prefixed onto all following routes defined in the scope. e.g. Mounting a callback `$fn` onto `/movies` will prefix `/movies` onto all following routes.
```php
$router->mount('/movies', function() use ($router) {
// will result in '/movies/'
$router->get('/', function() {
echo 'movies overview';
});
// will result in '/movies/id'
$router->get('/(\d+)', function($id) {
echo 'movie id ' . htmlentities($id);
});
});
```
Nesting of subroutes is possible, just define a second `$router->mount()` in the callable that's already contained within a preceding `$router->mount()`.
### `Class@Method` calls
We can route to the class action like so:
```php
$router->get('/(\d+)', '\App\Controllers\User@showProfile');
```
When a request matches the specified route URI, the `showProfile` method on the `User` class will be executed. The defined route parameters will be passed to the class method.
The method can be static (recommended) or non-static (not-recommended). In case of a non-static method, a new instance of the class will be created.
If most/all of your handling classes are in one and the same namespace, you can set the default namespace to use on your router instance via `setNamespace()`
```php
$router->setNamespace('\App\Controllers');
$router->get('/users/(\d+)', 'User@showProfile');
$router->get('/cars/(\d+)', 'Car@showProfile');
```
### Custom 404
The default 404 handler sets a 404 status code and exits. You can override this default 404 handler by using `$router->set404(callable);`
```php
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
// ... do something special here
});
```
You can also define multiple custom routes e.x. you want to define an `/api` route, you can print a custom 404 page:
```php
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
```
Also supported are `Class@Method` callables:
```php
$router->set404('\App\Controllers\Error@notFound');
```
The 404 handler will be executed when no route pattern was matched to the current URL.
💡 You can also manually trigger the 404 handler by calling `$router->trigger404()`
```php
$router->get('/([a-z0-9-]+)', function($id) use ($router) {
if (!Posts::exists($id)) {
$router->trigger404();
return;
}
// …
});
```
### Before Route Middlewares
`bramus/router` supports __Before Route Middlewares__, which are executed before the route handling is processed.
Like route handling functions, you hook a handling function to a combination of one or more HTTP request methods and a specific route pattern.
```php
$router->before('GET|POST', '/admin/.*', function() {
if (!isset($_SESSION['user'])) {
header('location: /auth/login');
exit();
}
});
```
Unlike route handling functions, more than one before route middleware is executed when more than one route match is found.
### Before Router Middlewares
Before route middlewares are route specific. Using a general route pattern (viz. _all URLs_), they can become __Before Router Middlewares__ _(in other projects sometimes referred to as before app middlewares)_ which are always executed, no matter what the requested URL is.
```php
$router->before('GET', '/.*', function() {
// ... this will always be executed
});
```
### After Router Middleware / Run Callback
Run one (1) middleware function, name the __After Router Middleware__ _(in other projects sometimes referred to as after app middlewares)_ after the routing was processed. Just pass it along the `$router->run()` function. The run callback is route independent.
```php
$router->run(function() { });
```
Note: If the route handling function has `exit()`ed the run callback won't be run.
### Overriding the request method
Use `X-HTTP-Method-Override` to override the HTTP Request Method. Only works when the original Request Method is `POST`. Allowed values for `X-HTTP-Method-Override` are `PUT`, `DELETE`, or `PATCH`.
### Subfolder support
Out-of-the box `bramus/router` will run in any (sub)folder you place it into … no adjustments to your code are needed. You can freely move your _entry script_ `index.php` around, and the router will automatically adapt itself to work relatively from the current folder's path by mounting all routes onto that __basePath__.
Say you have a server hosting the domain `www.example.org` using `public_html/` as its document root, with this little _entry script_ `index.php`:
```php
$router->get('/', function() { echo 'Index'; });
$router->get('/hello', function() { echo 'Hello!'; });
```
- If your were to place this file _(along with its accompanying `.htaccess` file or the like)_ at the document root level (e.g. `public_html/index.php`), `bramus/router` will mount all routes onto the domain root (e.g. `/`) and thus respond to `https://www.example.org/` and `https://www.example.org/hello`.
- If you were to move this file _(along with its accompanying `.htaccess` file or the like)_ into a subfolder (e.g. `public_html/demo/index.php`), `bramus/router` will mount all routes onto the current path (e.g. `/demo`) and thus repsond to `https://www.example.org/demo` and `https://www.example.org/demo/hello`. There's **no** need for `$router->mount(…)` in this case.
#### Disabling subfolder support
In case you **don't** want `bramus/router` to automatically adapt itself to the folder its being placed in, it's possible to manually override the _basePath_ by calling `setBasePath()`. This is necessary in the _(uncommon)_ situation where your _entry script_ and your _entry URLs_ are not tightly coupled _(e.g. when the entry script is placed into a subfolder that does not need be part of the URLs it responds to)_.
```php
// Override auto base path detection
$router->setBasePath('/');
$router->get('/', function() { echo 'Index'; });
$router->get('/hello', function() { echo 'Hello!'; });
$router->run();
```
If you were to place this file into a subfolder (e.g. `public_html/some/sub/folder/index.php`), it will still mount the routes onto the domain root (e.g. `/`) and thus respond to `https://www.example.org/` and `https://www.example.org/hello` _(given that your `.htaccess` file placed at the document root level rewrites requests to it)_
## Integration with other libraries
Integrate other libraries with `bramus/router` by making good use of the `use` keyword to pass dependencies into the handling functions.
```php
$tpl = new \Acme\Template\Template();
$router->get('/', function() use ($tpl) {
$tpl->load('home.tpl');
$tpl->setdata(array(
'name' => 'Bramus!'
));
});
$router->run(function() use ($tpl) {
$tpl->display();
});
```
Given this structure it is still possible to manipulate the output from within the After Router Middleware
## A note on working with PUT
There's no such thing as `$_PUT` in PHP. One must fake it:
```php
$router->put('/movies/(\d+)', function($id) {
// Fake $_PUT
$_PUT = array();
parse_str(file_get_contents('php://input'), $_PUT);
// ...
});
```
## A note on making HEAD requests
When making `HEAD` requests all output will be buffered to prevent any content trickling into the response body, as defined in [RFC2616 (Hypertext Transfer Protocol -- HTTP/1.1)](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4):
> The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
To achieve this, `bramus/router` but will internally re-route `HEAD` requests to their equivalent `GET` request and automatically suppress all output.
## Unit Testing & Code Coverage
`bramus/router` ships with unit tests using [PHPUnit](https://github.com/sebastianbergmann/phpunit/).
- If PHPUnit is installed globally run `phpunit` to run the tests.
- If PHPUnit is not installed globally, install it locally throuh composer by running `composer install --dev`. Run the tests themselves by calling `vendor/bin/phpunit`.
The included `composer.json` will also install `php-code-coverage` which allows one to generate a __Code Coverage Report__. Run `phpunit --coverage-html ./tests-report` (XDebug required), a report will be placed into the `tests-report` subfolder.
## Acknowledgements
`bramus/router` is inspired upon [Klein](https://github.com/chriso/klein.php), [Ham](https://github.com/radiosilence/Ham), and [JREAM/route](https://bitbucket.org/JREAM/route) . Whilst Klein provides lots of features it is not object oriented. Whilst Ham is Object Oriented, it's bad at _separation of concerns_ as it also provides templating within the routing class. Whilst JREAM/route is a good starting point it is limited in what it does (only GET routes for example).
## License
`bramus/router` is released under the MIT public license. See the enclosed `LICENSE` for details.
@@ -0,0 +1,31 @@
{
"name": "bramus/router",
"description": "A lightweight and simple object oriented PHP Router",
"keywords": ["router", "routing"],
"homepage": "https://github.com/bramus/router",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Bram(us) Van Damme",
"email": "bramus@bram.us",
"homepage": "http://www.bram.us"
}
],
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8",
"phpunit/php-code-coverage": "~2.0",
"friendsofphp/php-cs-fixer": "~2.14"
},
"autoload": {
"psr-0": {"Bramus": "src/"}
},
"scripts": {
"test": "./vendor/bin/phpunit --colors=always",
"lint": "php-cs-fixer fix --diff --dry-run",
"fix": "php-cs-fixer fix"
}
}
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
@@ -0,0 +1,82 @@
<?php
// In case one is using PHP 5.4+'s built-in server
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Include the Router class
// @note: it's recommended to just use the composer autoloader when working with other packages too
require_once __DIR__ . '/../src/Bramus/Router/Router.php';
/**
* A Multilingual Router
*/
class MultilangRouter extends \Bramus\Router\Router
{
/**
* The Default langauge
* @var string
*/
private $defaultLanguage;
/**
* List of allowed languages
* @var array
*/
private $allowedLanguages = array();
/**
* A Multilingual Router
* @param array $allowedLanguages
* @param string $defaultLanguage
*/
public function __construct(array $allowedLanguages, $defaultLanguage)
{
// Store passed in data
$this->allowedLanguages = $allowedLanguages;
$this->defaultLanguage = (in_array($defaultLanguage, $allowedLanguages) ? $defaultLanguage : $allowedLanguages[0]);
// Visiting the root? Redirect to the default language index
$this->match('GET|POST|PUT|DELETE|HEAD', '/', function () {
header('location: /' . $this->defaultLanguage);
exit();
});
// Create a before handler to make sure the language checks out when visiting anything but the root.
// If the language doesn't check out, redirect to the default language index
$this->before('GET|POST|PUT|DELETE|HEAD', '/([a-z0-9_-]+)(/.*)?', function ($language, $slug = null) {
// The given language does not appear in the array of allowed languages
if (!in_array($language, $this->allowedLanguages)) {
header('location: /' . $this->defaultLanguage);
exit();
}
});
}
}
// Create a Router
$router = new MultilangRouter(
array('en','nl','fr'), //= allowed languages
'nl' // = default language
);
$router->get('/([a-z0-9_-]+)', function ($language) {
exit('This is the ' . htmlentities($language) . ' index');
});
$router->get('/([a-z0-9_-]+)/([a-z0-9_-]+)', function ($language, $slug) {
exit('This is the ' . htmlentities($language) . ' version of ' . htmlentities($slug));
});
$router->get('/([a-z0-9_-]+)/(.*)', function ($language, $slug) {
exit('This is the ' . htmlentities($language) . ' version of ' . htmlentities($slug) . ' (multiple segments allowed)');
});
// Thunderbirds are go!
$router->run();
// EOF
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
@@ -0,0 +1,134 @@
<?php
// In case one is using PHP 5.4's built-in server
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Include the Router class
// @note: it's recommended to just use the composer autoloader when working with other packages too
require_once __DIR__ . '/../src/Bramus/Router/Router.php';
// Create a Router
$router = new \Bramus\Router\Router();
// Custom 404 Handler
$router->set404(function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '404, route not found!';
});
// custom 404
$router->set404('/test(/.*)?', function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '<h1><mark>404, route not found!</mark></h1>';
});
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
// Before Router Middleware
$router->before('GET', '/.*', function () {
header('X-Powered-By: bramus/router');
});
// Static route: / (homepage)
$router->get('/', function () {
echo '<h1>bramus/router</h1>
<p>Try these routes:<p>
<ul>
<li><a href="/hello/joe">/hello/<em>name</em></a></li>
<li><a href="/blog">/blog</a></li>
<li><a href="/blog/'.date('Y').'">/blog/<em>year</em></a></li>
<li><a href="/blog/'.date('Y').'/'.date('m').'">/blog/<em>year</em>/<em>month</em></a></li>
<li><a href="/blog/'.date('Y').'/'.date('m').'/'.date('d').'">/blog/<em>year</em>/<em>month</em>/<em>day</em></a></li>
<li><a href="/movies">/movies</a></li>
<li><a href="/movies/23">/movies/<em>id</em></a></li>
</ul>
<br><br>
<p>Custom error routes</p>
<ul>
<li><a href="/something">/*</a> <em>Normal 404</em></li>
<li><a href="/test">/test/*</a> <em>Custom 404</em></li>
<li><a href="/api/getUser">/api/getUser</a> <em>API 404</em></li>
</ul>
';
});
// Static route: /hello
$router->get('/hello', function () {
echo '<h1>bramus/router</h1><p>Visit <code>/hello/<em>name</em></code> to get your Hello World mojo on!</p>';
});
// Dynamic route: /hello/name
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . htmlentities($name);
});
// Dynamic route: /ohai/name/in/parts
$router->get('/ohai/(.*)', function ($url) {
echo 'Ohai ' . htmlentities($url);
});
// Dynamic route with (successive) optional subpatterns: /blog(/year(/month(/day(/slug))))
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if (!$year) {
echo 'Blog overview';
return;
}
if (!$month) {
echo 'Blog year overview (' . $year . ')';
return;
}
if (!$day) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if (!$slug) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Subrouting
$router->mount('/movies', function () use ($router) {
// will result in '/movies'
$router->get('/', function () {
echo 'movies overview';
});
// will result in '/movies'
$router->post('/', function () {
echo 'add movie';
});
// will result in '/movies/id'
$router->get('/(\d+)', function ($id) {
echo 'movie id ' . htmlentities($id);
});
// will result in '/movies/id'
$router->put('/(\d+)', function ($id) {
echo 'Update movie id ' . htmlentities($id);
});
});
// Thunderbirds are go!
$router->run();
// EOF
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="Router Tests">
<directory>tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
@@ -0,0 +1,535 @@
<?php
/**
* @author Bram(us) Van Damme <bramus@bram.us>
* @copyright Copyright (c), 2013 Bram(us) Van Damme
* @license MIT public license
*/
namespace Bramus\Router;
/**
* Class Router.
*/
class Router
{
/**
* @var array The route patterns and their handling functions
*/
private $afterRoutes = array();
/**
* @var array The before middleware route patterns and their handling functions
*/
private $beforeRoutes = array();
/**
* @var array [object|callable] The function to be executed when no route has been matched
*/
protected $notFoundCallback = [];
/**
* @var string Current base route, used for (sub)route mounting
*/
private $baseRoute = '';
/**
* @var string The Request Method that needs to be handled
*/
private $requestedMethod = '';
/**
* @var string The Server Base Path for Router Execution
*/
private $serverBasePath;
/**
* @var string Default Controllers Namespace
*/
private $namespace = '';
/**
* Store a before middleware route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function before($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->beforeRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
/**
* Store a route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function match($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->afterRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
/**
* Shorthand for a route accessed using any method.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function all($pattern, $fn)
{
$this->match('GET|POST|PUT|DELETE|OPTIONS|PATCH|HEAD', $pattern, $fn);
}
/**
* Shorthand for a route accessed using GET.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function get($pattern, $fn)
{
$this->match('GET', $pattern, $fn);
}
/**
* Shorthand for a route accessed using POST.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function post($pattern, $fn)
{
$this->match('POST', $pattern, $fn);
}
/**
* Shorthand for a route accessed using PATCH.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function patch($pattern, $fn)
{
$this->match('PATCH', $pattern, $fn);
}
/**
* Shorthand for a route accessed using DELETE.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function delete($pattern, $fn)
{
$this->match('DELETE', $pattern, $fn);
}
/**
* Shorthand for a route accessed using PUT.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function put($pattern, $fn)
{
$this->match('PUT', $pattern, $fn);
}
/**
* Shorthand for a route accessed using OPTIONS.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function options($pattern, $fn)
{
$this->match('OPTIONS', $pattern, $fn);
}
/**
* Mounts a collection of callbacks onto a base route.
*
* @param string $baseRoute The route sub pattern to mount the callbacks on
* @param callable $fn The callback method
*/
public function mount($baseRoute, $fn)
{
// Track current base route
$curBaseRoute = $this->baseRoute;
// Build new base route string
$this->baseRoute .= $baseRoute;
// Call the callable
call_user_func($fn);
// Restore original base route
$this->baseRoute = $curBaseRoute;
}
/**
* Get all request headers.
*
* @return array The request headers
*/
public function getRequestHeaders()
{
$headers = array();
// If getallheaders() is available, use that
if (function_exists('getallheaders')) {
$headers = getallheaders();
// getallheaders() can return false if something went wrong
if ($headers !== false) {
return $headers;
}
}
// Method getallheaders() not available or went wrong: manually extract 'm
foreach ($_SERVER as $name => $value) {
if ((substr($name, 0, 5) == 'HTTP_') || ($name == 'CONTENT_TYPE') || ($name == 'CONTENT_LENGTH')) {
$headers[str_replace(array(' ', 'Http'), array('-', 'HTTP'), ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
/**
* Get the request method used, taking overrides into account.
*
* @return string The Request method to handle
*/
public function getRequestMethod()
{
// Take the method as found in $_SERVER
$method = $_SERVER['REQUEST_METHOD'];
// If it's a HEAD request override it to being GET and prevent any output, as per HTTP Specification
// @url http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_start();
$method = 'GET';
}
// If it's a POST request, check for a method override header
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$headers = $this->getRequestHeaders();
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
$method = $headers['X-HTTP-Method-Override'];
}
}
return $method;
}
/**
* Set a Default Lookup Namespace for Callable methods.
*
* @param string $namespace A given namespace
*/
public function setNamespace($namespace)
{
if (is_string($namespace)) {
$this->namespace = $namespace;
}
}
/**
* Get the given Namespace before.
*
* @return string The given Namespace if exists
*/
public function getNamespace()
{
return $this->namespace;
}
/**
* Execute the router: Loop all defined before middleware's and routes, and execute the handling function if a match was found.
*
* @param object|callable $callback Function to be executed after a matching route was handled (= after router middleware)
*
* @return bool
*/
public function run($callback = null)
{
// Define which method we need to handle
$this->requestedMethod = $this->getRequestMethod();
// Handle all before middlewares
if (isset($this->beforeRoutes[$this->requestedMethod])) {
$this->handle($this->beforeRoutes[$this->requestedMethod]);
}
// Handle all routes
$numHandled = 0;
if (isset($this->afterRoutes[$this->requestedMethod])) {
$numHandled = $this->handle($this->afterRoutes[$this->requestedMethod], true);
}
// If no route was handled, trigger the 404 (if any)
if ($numHandled === 0) {
$this->trigger404($this->afterRoutes[$this->requestedMethod]);
} // If a route was handled, perform the finish callback (if any)
else {
if ($callback && is_callable($callback)) {
$callback();
}
}
// If it originally was a HEAD request, clean up after ourselves by emptying the output buffer
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_end_clean();
}
// Return true if a route was handled, false otherwise
return $numHandled !== 0;
}
/**
* Set the 404 handling function.
*
* @param object|callable|string $match_fn The function to be executed
* @param object|callable $fn The function to be executed
*/
public function set404($match_fn, $fn = null)
{
if (!is_null($fn)) {
$this->notFoundCallback[$match_fn] = $fn;
} else {
$this->notFoundCallback['/'] = $match_fn;
}
}
/**
* Triggers 404 response
*
* @param string $pattern A route pattern such as /about/system
*/
public function trigger404($match = null){
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
// handle 404 pattern
if (count($this->notFoundCallback) > 0)
{
// loop fallback-routes
foreach ($this->notFoundCallback as $route_pattern => $route_callable) {
// matches result
$matches = [];
// check if there is a match and get matches as $matches (pointer)
$is_match = $this->patternMatches($route_pattern, $this->getCurrentUri(), $matches, PREG_OFFSET_CAPTURE);
// is fallback route match?
if ($is_match) {
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
if ($matches[$index + 1][0][1] > -1) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
}
} // We have no following parameters: return the whole lot
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));
$this->invoke($route_callable);
++$numHandled;
}
}
}
if (($numHandled == 0) && (isset($this->notFoundCallback['/']))) {
$this->invoke($this->notFoundCallback['/']);
} elseif ($numHandled == 0) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
}
}
/**
* Replace all curly braces matches {} into word patterns (like Laravel)
* Checks if there is a routing match
*
* @param $pattern
* @param $uri
* @param $matches
* @param $flags
*
* @return bool -> is match yes/no
*/
private function patternMatches($pattern, $uri, &$matches, $flags)
{
// Replace all curly braces matches {} into word patterns (like Laravel)
$pattern = preg_replace('/\/{(.*?)}/', '/(.*?)', $pattern);
// we may have a match!
return boolval(preg_match_all('#^' . $pattern . '$#', $uri, $matches, PREG_OFFSET_CAPTURE));
}
/**
* Handle a a set of routes: if a match is found, execute the relating handling function.
*
* @param array $routes Collection of route patterns and their handling functions
* @param bool $quitAfterRun Does the handle function need to quit after one route was matched?
*
* @return int The number of routes handled
*/
private function handle($routes, $quitAfterRun = false)
{
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
// The current page URL
$uri = $this->getCurrentUri();
// Loop all routes
foreach ($routes as $route) {
// get routing matches
$is_match = $this->patternMatches($route['pattern'], $uri, $matches, PREG_OFFSET_CAPTURE);
// is there a valid match?
if ($is_match) {
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
if ($matches[$index + 1][0][1] > -1) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
}
} // We have no following parameters: return the whole lot
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));
// Call the handling function with the URL parameters if the desired input is callable
$this->invoke($route['fn'], $params);
++$numHandled;
// If we need to quit, then quit
if ($quitAfterRun) {
break;
}
}
}
// Return the number of routes handled
return $numHandled;
}
private function invoke($fn, $params = array())
{
if (is_callable($fn)) {
call_user_func_array($fn, $params);
}
// If not, check the existence of special parameters
elseif (stripos($fn, '@') !== false) {
// Explode segments of given route
list($controller, $method) = explode('@', $fn);
// Adjust controller class if namespace has been set
if ($this->getNamespace() !== '') {
$controller = $this->getNamespace() . '\\' . $controller;
}
try {
$reflectedMethod = new \ReflectionMethod($controller, $method);
// Make sure it's callable
if ($reflectedMethod->isPublic() && (!$reflectedMethod->isAbstract())) {
if ($reflectedMethod->isStatic()) {
forward_static_call_array(array($controller, $method), $params);
} else {
// Make sure we have an instance, because a non-static method must not be called statically
if (\is_string($controller)) {
$controller = new $controller();
}
call_user_func_array(array($controller, $method), $params);
}
}
} catch (\ReflectionException $reflectionException) {
// The controller class is not available or the class does not have the method $method
}
}
}
/**
* Define the current relative URI.
*
* @return string
*/
public function getCurrentUri()
{
// Get the current Request URI and remove rewrite base path from it (= allows one to run the router in a sub folder)
$uri = substr(rawurldecode($_SERVER['REQUEST_URI']), strlen($this->getBasePath()));
// Don't take query params into account on the URL
if (strstr($uri, '?')) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
// Remove trailing slash + enforce a slash at the start
return '/' . trim($uri, '/');
}
/**
* Return server base Path, and define it if isn't defined.
*
* @return string
*/
public function getBasePath()
{
// Check if server base path is defined, if not define it.
if ($this->serverBasePath === null) {
$this->serverBasePath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
}
return $this->serverBasePath;
}
/**
* Explicilty sets the server base path. To be used when your entry script path differs from your entry URLs.
* @see https://github.com/bramus/router/issues/82#issuecomment-466956078
*
* @param string
*/
public function setBasePath($serverBasePath)
{
$this->serverBasePath = $serverBasePath;
}
}
@@ -0,0 +1,959 @@
<?php
namespace {
class Handler
{
public function notfound()
{
echo 'route not found';
}
}
class RouterTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
// Clear SCRIPT_NAME because bramus/router tries to guess the subfolder the script is run in
$_SERVER['SCRIPT_NAME'] = '/index.php';
// Default request method to GET
$_SERVER['REQUEST_METHOD'] = 'GET';
// Default SERVER_PROTOCOL method to HTTP/1.1
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
}
protected function tearDown()
{
// nothing
}
public function testInit()
{
$this->assertInstanceOf('\Bramus\Router\Router', new \Bramus\Router\Router());
}
public function testUri()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/about/whatever';
$method = new ReflectionMethod(
'\Bramus\Router\Router',
'getCurrentUri'
);
$method->setAccessible(true);
$this->assertEquals(
'/about/whatever',
$method->invoke(new \Bramus\Router\Router())
);
}
public function testBasePathOverride()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/public/index.php';
$_SERVER['REQUEST_URI'] = '/about';
$router->setBasePath('/');
$this->assertEquals(
'/',
$router->getBasePath()
);
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBasePathThatContainsEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/💩/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/%F0%9F%92%A9/about';
// Test the /hello/bramus route
ob_start();
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testStaticRoute()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testStaticRouteUsingShorthand()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/about', function () {
echo 'about';
});
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testRequestMethods()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'get';
});
$router->post('/', function () {
echo 'post';
});
$router->put('/', function () {
echo 'put';
});
$router->patch('/', function () {
echo 'patch';
});
$router->delete('/', function () {
echo 'delete';
});
$router->options('/', function () {
echo 'options';
});
// Test GET
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('get', ob_get_contents());
// Test POST
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('post', ob_get_contents());
// Test PUT
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PUT';
$router->run();
$this->assertEquals('put', ob_get_contents());
// Test PATCH
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$router->run();
$this->assertEquals('patch', ob_get_contents());
// Test DELETE
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$router->run();
$this->assertEquals('delete', ob_get_contents());
// Test OPTIONS
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'OPTIONS';
$router->run();
$this->assertEquals('options', ob_get_contents());
// Test HEAD
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'HEAD';
$router->run();
$this->assertEquals('', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testShorthandAll()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->all('/', function () {
echo 'all';
});
$_SERVER['REQUEST_URI'] = '/';
// Test GET
ob_start();
$_SERVER['REQUEST_METHOD'] = 'GET';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test POST
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test PUT
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PUT';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test DELETE
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test OPTIONS
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'OPTIONS';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test PATCH
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test HEAD
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'HEAD';
$router->run();
$this->assertEquals('', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRoute()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithMultiple()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)/(\w+)', function ($name, $lastname) {
echo 'Hello ' . $name . ' ' . $lastname;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutes()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{name}/{lastname}', function ($name, $lastname) {
echo 'Hello ' . $name . ' ' . $lastname;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithNonAZCharsInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{arg1}/{arg2}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithCyrillicCharactersInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{това}/{това}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithEmojiInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{😂}/{😅}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithCyrillicCharacters()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/bg/{arg}', function ($arg) {
echo 'BG: ' . $arg;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/bg/това';
$router->run();
$this->assertEquals('BG: това', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithMultipleCyrillicCharacters()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/bg/{arg}/{arg}', function ($arg1, $arg2) {
echo 'BG: ' . $arg1 . ' - ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/bg/това/слъг';
$router->run();
$this->assertEquals('BG: това - слъг', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/emoji/{emoji}', function ($emoji) {
echo 'Emoji: ' . $emoji;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/emoji/%F0%9F%92%A9'; // 💩
$router->run();
$this->assertEquals('Emoji: 💩', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithEmojiCombinedWithBasePathThatContainsEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/emoji/{emoji}', function ($emoji) {
echo 'Emoji: ' . $emoji;
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/💩/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/%F0%9F%92%A9/emoji/%F0%9F%A4%AF'; // 🤯
// Test the /hello/bramus route
ob_start();
$router->run();
$this->assertEquals('Emoji: 🤯', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithOptionalSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello(/\w+)?', function ($name = null) {
echo 'Hello ' . (($name) ? $name : 'stranger');
});
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello';
$router->run();
$this->assertEquals('Hello stranger', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithMultipleSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/(.*)/page([0-9]+)', function ($place, $page) {
echo 'Hello ' . $place . ' page : ' . $page;
});
// Test the /hello/bramus/page3 route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/page3';
$router->run();
$this->assertEquals('Hello hello/bramus page : 3', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithOptionalNestedSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if ($year === null) {
echo 'Blog overview';
return;
}
if ($month === null) {
echo 'Blog year overview (' . $year . ')';
return;
}
if ($day === null) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if ($slug === null) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Test the /blog route
ob_start();
$_SERVER['REQUEST_URI'] = '/blog';
$router->run();
$this->assertEquals('Blog overview', ob_get_contents());
// Test the /blog/year route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983';
$router->run();
$this->assertEquals('Blog year overview (1983)', ob_get_contents());
// Test the /blog/year/month route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12';
$router->run();
$this->assertEquals('Blog month overview (1983-12)', ob_get_contents());
// Test the /blog/year/month/day route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12/26';
$router->run();
$this->assertEquals('Blog day overview (1983-12-26)', ob_get_contents());
// Test the /blog/year/month/day/slug route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12/26/bramus';
$router->run();
$this->assertEquals('Blogpost bramus detail (1983-12-26)', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithNestedOptionalSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello(/\w+(/\w+)?)?', function ($name1 = null, $name2 = null) {
echo 'Hello ' . (($name1) ? $name1 : 'stranger') . ' ' . (($name2) ? $name2 : 'stranger');
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus stranger', ob_get_contents());
// Test the /hello/bramus/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/hello/bramus/bramus';
$router->run();
$this->assertEquals('Hello bramus bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithWildcard()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('(.*)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello hello/bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithPartialWildcard()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(.*)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus/sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404(function () {
echo 'route not found';
});
$router->set404('/api(/.*)?', function () {
echo 'api route not found';
});
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Test the custom api 404
ob_clean();
$_SERVER['REQUEST_URI'] = '/api/getUser';
$router->run();
$this->assertEquals('api route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithClassAtMethod()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404('Handler@notFound');
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithClassAtStaticMethod()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404('Handler@notFound');
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithManualTrigger()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function() use ($router) {
$router->trigger404();
});
$router->set404(function () {
echo 'route not found';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBeforeRouterMiddleware()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->before('GET|POST', '/.*', function () {
echo 'before ';
});
$router->get('/', function () {
echo 'root';
});
$router->get('/about', function () {
echo 'about';
});
$router->get('/contact', function () {
echo 'contact';
});
$router->post('/post', function () {
echo 'post';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('before root', ob_get_contents());
// Test the /about route
ob_clean();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('before about', ob_get_contents());
// Test the /contact route
ob_clean();
$_SERVER['REQUEST_URI'] = '/contact';
$router->run();
$this->assertEquals('before contact', ob_get_contents());
// Test the /post route
ob_clean();
$_SERVER['REQUEST_URI'] = '/post';
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('before post', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testAfterRouterMiddleware()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run(function () {
echo 'finished';
});
$this->assertEquals('homefinished', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBasicController()
{
$router = new \Bramus\Router\Router();
$router->get('/show/(.*)', 'RouterTestController@show');
ob_start();
$_SERVER['REQUEST_URI'] = '/show/foo';
$router->run();
$this->assertEquals('foo', ob_get_contents());
// cleanup
ob_end_clean();
}
public function testDefaultNamespace()
{
$router = new \Bramus\Router\Router();
$router->setNamespace('\Hello');
$router->get('/show/(.*)', 'HelloRouterTestController@show');
ob_start();
$_SERVER['REQUEST_URI'] = '/show/foo';
$router->run();
$this->assertEquals('foo', ob_get_contents());
// cleanup
ob_end_clean();
}
public function testSubfolders()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
// Test the / route in a fake subfolder
ob_start();
$_SERVER['SCRIPT_NAME'] = '/about/index.php';
$_SERVER['REQUEST_URI'] = '/about/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testSubrouteMouting()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->mount('/movies', function () use ($router) {
$router->get('/', function () {
echo 'overview';
});
$router->get('/(\d+)', function ($id) {
echo htmlentities($id);
});
});
// Test the /movies route
ob_start();
$_SERVER['REQUEST_URI'] = '/movies';
$router->run();
$this->assertEquals('overview', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/movies/1';
$router->run();
$this->assertEquals('1', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testHttpMethodOverride()
{
// Fake the request method to being POST and override it
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';
$method = new ReflectionMethod(
'\Bramus\Router\Router',
'getRequestMethod'
);
$method->setAccessible(true);
$this->assertEquals(
'PUT',
$method->invoke(new \Bramus\Router\Router())
);
}
public function testControllerMethodReturningFalse()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/false', 'RouterTestController@returnFalse');
$router->get('/static-false', 'RouterTestController@staticReturnFalse');
// Test returnFalse
ob_start();
$_SERVER['REQUEST_URI'] = '/false';
$router->run();
$this->assertEquals('returnFalse', ob_get_contents());
// Test staticReturnFalse
ob_clean();
$_SERVER['REQUEST_URI'] = '/static-false';
$router->run();
$this->assertEquals('staticReturnFalse', ob_get_contents());
// Cleanup
ob_end_clean();
}
}
}
namespace {
class RouterTestController
{
public function show($id)
{
echo $id;
}
public function returnFalse()
{
echo 'returnFalse';
return false;
}
public static function staticReturnFalse()
{
echo 'staticReturnFalse';
return false;
}
}
}
namespace Hello {
class HelloRouterTestController
{
public function show($id)
{
echo $id;
}
}
}
// EOF
@@ -0,0 +1,3 @@
<?php
require 'src/Bramus/Router/Router.php';