mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 16:57:53 +00:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f285fd0ce | |||
| b7f5d31544 | |||
| 5086347802 | |||
| bb7991afdc | |||
| 796d01bc25 | |||
| 74187ee326 | |||
| 6e859e11ab | |||
| 6aa38cfa4c | |||
| 62f0075cf3 | |||
| a40f81d5fc | |||
| a5527a0e8c | |||
| 3c73de866e | |||
| 883d8a6b0e | |||
| 3a7b27796a |
@@ -34,6 +34,7 @@ If you want a great new feature or experience any issues what-so-ever, please fe
|
||||
- [Optional parameters](#optional-parameters)
|
||||
- [Regular expression constraints](#regular-expression-constraints)
|
||||
- [Regular expression route-match](#regular-expression-route-match)
|
||||
- [Custom regex for matching parameters](#custom-regex-for-matching-parameters)
|
||||
- [Named routes](#named-routes)
|
||||
- [Generating URLs To Named Routes](#generating-urls-to-named-routes)
|
||||
- [Router groups](#router-groups)
|
||||
@@ -381,7 +382,7 @@ The example below is using the following regular expression: `/ajax/([\w]+)/?([0
|
||||
|
||||
**Matches:** `/ajax/abc/`, `/ajax/abc/123/`
|
||||
|
||||
**Doesn't match:** `/ajax/`
|
||||
**Won't match:** `/ajax/`
|
||||
|
||||
Match groups specified in the regex will be passed on as parameters:
|
||||
|
||||
@@ -392,6 +393,35 @@ SimpleRouter::all('/ajax/abc/123', function($param1, $param2) {
|
||||
})->setMatch('/\/ajax\/([\w]+)\/?([0-9]+)?\/?/is');
|
||||
```
|
||||
|
||||
### Custom regex for matching parameters
|
||||
|
||||
By default simple-php-router uses the `\w` regular expression when matching parameters.
|
||||
This decision was made with speed and reliability in mind, as this match will match both letters, number and most of the used symbols on the internet.
|
||||
|
||||
However, sometimes it can be necessary to add a custom regular expression to match more advanced characters like `-` etc.
|
||||
|
||||
Instead of adding a custom regular expression to all your parameters, you can simply add a global regular expression which will be used on all the parameters on the route.
|
||||
|
||||
**Note:** If you the regular expression to be available across, we recommend using the global parameter on a group as demonstrated in the examples below.
|
||||
|
||||
#### Example
|
||||
|
||||
This example will ensure that all parameters use the `[\w\-]+` regular expression when parsing.
|
||||
|
||||
```php
|
||||
SimpleRouter::get('/path/{parameter}', 'VideoController@home', ['defaultParameterRegex' => '[\w\-]+']);
|
||||
```
|
||||
|
||||
You can also apply this setting to a group if you need multiple routes to use your custom regular expression when parsing parameters.
|
||||
|
||||
```php
|
||||
SimpleRouter::group(['defaultParameterRegex' => '[\w\-]+'], function() {
|
||||
|
||||
SimpleRouter::get('/path/{parameter}', 'VideoController@home');
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
## Named routes
|
||||
|
||||
Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition:
|
||||
@@ -1102,35 +1132,6 @@ $router->addRoute($route);
|
||||
|
||||
This section contains advanced tips & tricks on extending the usage for parameters.
|
||||
|
||||
### Custom default regex for matching parameters
|
||||
|
||||
By default simple-php-router uses the `\w` regular expression when matching parameters.
|
||||
This decision was made with speed and reliability in mind, as this match will match both letters, number and most of the used symbols on the internet.
|
||||
|
||||
However, sometimes it can be nessesary to add a custom regular expression to match more advanced characters like `-` etc.
|
||||
|
||||
Instead of adding a custom regular expression to all your parameters, you can simply add a global regular expression which will be used on all the parameters on the route.
|
||||
|
||||
**Note:** If you the regular expression to be available across, we recommend using the global parameter on a group as demonstrated in the examples below.
|
||||
|
||||
#### Route
|
||||
|
||||
This example will ensure that all parameters use the `[\w\-]+` regular expression when parsing.
|
||||
|
||||
```php
|
||||
SimpleRouter::get('/path/{parameter}', 'VideoController@home', ['defaultParameterRegex' => '[\w\-]+']);
|
||||
```
|
||||
|
||||
You can also apply this setting to a group if you need multiple routes to use your custom regular expression when parsing parameters.
|
||||
|
||||
```php
|
||||
SimpleRouter::group(['defaultParameterRegex' => '[\w\-]+'], function() {
|
||||
|
||||
SimpleRouter::get('/path/{parameter}', 'VideoController@home');
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
## Extending
|
||||
|
||||
This is a simple example of an integration into a framework.
|
||||
|
||||
@@ -92,7 +92,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
* Used when calling the url() helper.
|
||||
*
|
||||
* @param string|null $method
|
||||
* @param array|null $parameters
|
||||
* @param string|array|null $parameters
|
||||
* @param string|null $name
|
||||
* @return string
|
||||
*/
|
||||
@@ -123,11 +123,17 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
$param = $keys[$i];
|
||||
$value = $value = ($parameters !== null && array_key_exists($param, $parameters)) ? $parameters[$param] : $params[$param];
|
||||
|
||||
/* If parameter is specifically set to null - use the original-defined value */
|
||||
if ($value === null && isset($this->originalParameters[$param])) {
|
||||
$value = $this->originalParameters[$param];
|
||||
if ($parameters === '' || (is_array($parameters) && count($parameters) === 0)) {
|
||||
$value = '';
|
||||
} else {
|
||||
$p = (array)$parameters;
|
||||
$value = array_key_exists($param, $p) ? $p[$param] : $params[$param];
|
||||
|
||||
/* If parameter is specifically set to null - use the original-defined value */
|
||||
if ($value === null && isset($this->originalParameters[$param])) {
|
||||
$value = $this->originalParameters[$param];
|
||||
}
|
||||
}
|
||||
|
||||
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
|
||||
@@ -138,6 +144,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
}
|
||||
}
|
||||
|
||||
$url = '/' . ltrim($url, '/');
|
||||
$url .= join('/', $unknownParams);
|
||||
|
||||
return rtrim($url, '/') . '/';
|
||||
|
||||
@@ -34,7 +34,12 @@ abstract class Route implements IRoute
|
||||
* @var bool
|
||||
*/
|
||||
protected $filterEmptyParams = false;
|
||||
protected $defaultParameterRegex = null;
|
||||
|
||||
/**
|
||||
* Default regular expression used for parsing parameters.
|
||||
* @var string|null
|
||||
*/
|
||||
protected $defaultParameterRegex;
|
||||
protected $paramModifiers = '{}';
|
||||
protected $paramOptionalSymbol = '?';
|
||||
protected $group;
|
||||
@@ -71,9 +76,7 @@ abstract class Route implements IRoute
|
||||
if (is_callable($callback) === true) {
|
||||
|
||||
/* When the callback is a function */
|
||||
call_user_func_array($callback, $this->getParameters());
|
||||
|
||||
return;
|
||||
return call_user_func_array($callback, $this->getParameters());
|
||||
|
||||
}
|
||||
|
||||
@@ -101,7 +104,7 @@ abstract class Route implements IRoute
|
||||
});
|
||||
}
|
||||
|
||||
call_user_func_array([$class, $method], $parameters);
|
||||
return call_user_func_array([$class, $method], $parameters);
|
||||
}
|
||||
|
||||
protected function parseParameters($route, $url, $parameterRegex = null)
|
||||
@@ -110,6 +113,9 @@ abstract class Route implements IRoute
|
||||
|
||||
$parameters = [];
|
||||
|
||||
// Ensures that hostnames/domains will work with parameters
|
||||
$url = '/' . ltrim($url, '/');
|
||||
|
||||
if (preg_match_all('/' . $regex . '/', $route, $parameters)) {
|
||||
|
||||
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', rtrim($route, '/'));
|
||||
@@ -135,7 +141,7 @@ abstract class Route implements IRoute
|
||||
}
|
||||
}
|
||||
|
||||
$regex = sprintf('\-?\/?(?P<%s>%s)', $name, $regex) . $parameters[2][$key];
|
||||
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
|
||||
|
||||
}
|
||||
|
||||
@@ -148,7 +154,7 @@ abstract class Route implements IRoute
|
||||
$urlRegex = preg_quote($route, '/');
|
||||
}
|
||||
|
||||
if (preg_match('/^' . $urlRegex . '(\/?)$/', $url, $matches) > 0) {
|
||||
if (preg_match('/^' . $urlRegex . '\/?$/', $url, $matches) > 0) {
|
||||
|
||||
$values = [];
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
if (strpos($name, '.') !== false) {
|
||||
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
|
||||
if ($found !== false) {
|
||||
$method = $found;
|
||||
$method = (string)$found;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -248,9 +248,7 @@ class Router
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
$rewriteRoute->renderRoute($this->request);
|
||||
|
||||
return;
|
||||
return $rewriteRoute->renderRoute($this->request);
|
||||
}
|
||||
|
||||
/* If the request has changed */
|
||||
@@ -267,7 +265,7 @@ class Router
|
||||
/* Render route */
|
||||
$routeNotAllowed = false;
|
||||
$this->request->setLoadedRoute($route);
|
||||
$route->renderRoute($this->request);
|
||||
return $route->renderRoute($this->request);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -295,6 +293,11 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Exception $e
|
||||
* @throws HttpException
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected function handleException(\Exception $e)
|
||||
{
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
@@ -320,9 +323,7 @@ class Router
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
$rewriteRoute->renderRoute($this->request);
|
||||
|
||||
return;
|
||||
return $rewriteRoute->renderRoute($this->request);
|
||||
}
|
||||
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
@@ -49,7 +49,7 @@ class SimpleRouter
|
||||
*/
|
||||
public static function start()
|
||||
{
|
||||
static::router()->routeRequest();
|
||||
echo static::router()->routeRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,66 @@ require_once 'Helpers/TestRouter.php';
|
||||
class RouterUrlTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testIssue253()
|
||||
{
|
||||
TestRouter::get('/', 'DummyController@method1');
|
||||
TestRouter::get('/page/{id?}', 'DummyController@method1');
|
||||
TestRouter::get('/test-output', function() {
|
||||
return 'return value';
|
||||
});
|
||||
|
||||
TestRouter::debugNoReset('/page/22', 'get');
|
||||
$this->assertEquals('/page/{id?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/', 'get');
|
||||
$this->assertEquals('/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
$output = TestRouter::debugOutput('/test-output', 'get');
|
||||
$this->assertEquals('return value', $output);
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testUnicodeCharacters()
|
||||
{
|
||||
// Test spanish characters
|
||||
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
|
||||
TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
|
||||
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
// Test danish characters
|
||||
TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
|
||||
TestRouter::debugNoReset('/kategori/økse', 'get');
|
||||
$this->assertEquals('/kategori/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testOptionalParameters()
|
||||
{
|
||||
TestRouter::get('/aviso/legal', 'DummyController@method1');
|
||||
TestRouter::get('/aviso/{aviso}', 'DummyController@method1');
|
||||
TestRouter::get('/pagina/{pagina}', 'DummyController@method1');
|
||||
TestRouter::get('/{pagina?}', 'DummyController@method1');
|
||||
|
||||
TestRouter::debugNoReset('/aviso/optional', 'get');
|
||||
$this->assertEquals('/aviso/{aviso}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/pagina/optional', 'get');
|
||||
$this->assertEquals('/pagina/{pagina}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/optional', 'get');
|
||||
$this->assertEquals('/{pagina?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/avisolegal', 'get');
|
||||
$this->assertNotEquals('/aviso/{aviso}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/avisolegal', 'get');
|
||||
$this->assertEquals('/{pagina?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testSimilarUrls()
|
||||
{
|
||||
// Match normal route on alias
|
||||
|
||||
Reference in New Issue
Block a user