diff --git a/.codeclimate.yml b/.codeclimate.yml
deleted file mode 100644
index 467daf9..0000000
--- a/.codeclimate.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-engines:
- phpmd:
- enabled: true
- checks:
- Design/TooManyPublicMethods:
- enabled: true
- Naming/ShortVariable:
- enabled: true
- CleanCode/StaticAccess:
- enabled: true
- Controversial/CamelCaseMethodName:
- enabled: true
- fixme:
- enabled: true
- duplication:
- enabled: true
- config:
- languages:
- - php:
-ratings:
- paths:
- - src/**
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..e2ccc7b
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,59 @@
+name: CI
+
+on: [push, pull_request]
+
+jobs:
+ build-test:
+ runs-on: ${{ matrix.os }}
+
+ env:
+ PHP_EXTENSIONS: json
+ PHP_INI_VALUES: assert.exception=1, zend.assertions=1
+
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ - windows-latest
+ php-version:
+ - 7.1
+ - 7.4
+ phpunit-version:
+ - 7.5.20
+ dependencies:
+ - lowest
+ - highest
+ name: PHPUnit Tests
+ steps:
+ - name: Configure git to avoid issues with line endings
+ if: matrix.os == 'windows-latest'
+ run: git config --global core.autocrlf false
+ - name: Checkout
+ uses: actions/checkout@v2
+ - name: Setup PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer:v5, phpunit:${{ matrix.phpunit-versions }}
+ coverage: xdebug
+ extensions: ${{ env.PHP_EXTENSIONS }}
+ ini-values: ${{ env.PHP_INI_VALUES }}
+ - name: Get composer cache directory
+ id: composer-cache
+ run: echo "::set-output name=dir::$(composer config cache-files-dir)"
+ - name: Cache dependencies
+ uses: actions/cache@v2
+ with:
+ path: ${{ steps.composer-cache.outputs.dir }}
+ key: php${{ matrix.php-version }}-composer-${{ matrix.dependencies }}-${{ hashFiles('**/composer.json') }}
+ restore-keys: |
+ php${{ matrix.php-version }}-composer-${{ matrix.dependencies }}-
+ - name: Install lowest dependencies with composer
+ if: matrix.dependencies == 'lowest'
+ run: composer update --no-ansi --no-interaction --no-progress --prefer-lowest
+ - name: Install highest dependencies with composer
+ if: matrix.dependencies == 'highest'
+ run: composer update --no-ansi --no-interaction --no-progress
+ - name: Run tests with phpunit
+ run: composer test
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index f3bdaaa..d85ecfa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
composer.lock
vendor/
-tests/tmp/*
\ No newline at end of file
+.idea/
+.phpunit.result.cache
\ No newline at end of file
diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml
deleted file mode 100644
index 91dfc80..0000000
--- a/.idea/codeStyles/codeStyleConfig.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/dictionaries/simon.xml b/.idea/dictionaries/simon.xml
deleted file mode 100644
index 87f7ef2..0000000
--- a/.idea/dictionaries/simon.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
- bootmanager
- bootmanagers
- csrf
- middlewares
- pecee
- urldecode
-
-
-
\ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
deleted file mode 100644
index 15a15b2..0000000
--- a/.idea/encodings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/.idea/markdown-navigator.xml b/.idea/markdown-navigator.xml
deleted file mode 100644
index e41dd85..0000000
--- a/.idea/markdown-navigator.xml
+++ /dev/null
@@ -1,72 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/markdown-navigator/profiles_settings.xml b/.idea/markdown-navigator/profiles_settings.xml
deleted file mode 100644
index 57927c5..0000000
--- a/.idea/markdown-navigator/profiles_settings.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-
-
-
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
deleted file mode 100644
index a5ba0c2..0000000
--- a/.idea/modules.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/php-test-framework.xml b/.idea/php-test-framework.xml
deleted file mode 100644
index 82ec95c..0000000
--- a/.idea/php-test-framework.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/php.xml b/.idea/php.xml
deleted file mode 100644
index 02facb2..0000000
--- a/.idea/php.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/simple-php-router.iml b/.idea/simple-php-router.iml
deleted file mode 100644
index e5bc18a..0000000
--- a/.idea/simple-php-router.iml
+++ /dev/null
@@ -1,50 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
deleted file mode 100644
index 94a25f7..0000000
--- a/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
deleted file mode 100644
index c262aba..0000000
--- a/.idea/workspace.xml
+++ /dev/null
@@ -1,939 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- $PROJECT_DIR$/composer.json
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- options
- parent::set
- parseParameters
- stripos
- setPrefix
- var_dum
- parse
- getParams
- setQuery
- contains
- matchRoute
- ->getValue
- ->find
- function find
- Req
- value(
- file(
- setUrl
- TODO
- input()->get
- function get
- REQUEST_TYPE_
- or method
- setDebugEnabled
- debugEnabled
- optiona
- \/
- requirements
- ler = new I
- csrf_token
-
-
- D:\Workspace\simple-php-router\src\Pecee\SimpleRouter\Route
- D:\Workspace\simple-php-router\src
- D:\Workspace\simple-php-router\tests\Pecee\SimpleRouter\Dummy
- D:\Workspace\simple-php-router
- E:\Workspace\simple-php-router\tests
- E:\Workspace\simple-php-router\src\Pecee
- E:\Workspace\simple-php-router\tests\Pecee\SimpleRouter
- E:\Workspace\simple-php-router\src\Pecee\SimpleRouter\Route
- E:\Workspace\simple-php-router\src\Pecee\SimpleRouter
- E:\Workspace\simple-php-router\src
- E:\Workspace\simple-php-router
-
-
-
-
-
-
-
-
-
- false
-
- false
- false
- true
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 1502498236860
-
-
- 1502498236860
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.scrutinizer.yml b/.scrutinizer.yml
deleted file mode 100644
index 0608e7a..0000000
--- a/.scrutinizer.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-build:
- tests:
- override:
- -
- command: './vendor/bin/phpunit --coverage-clover=coverage.clover'
- coverage:
- file: 'coverage.clover'
- format: 'clover'
-checks:
- php:
- code_rating: true
- duplication: true
-
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 72c98f1..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-sudo: false
-
-language: php
-
-php:
- - 7.1
-
-before_script:
- - curl -sS http://getcomposer.org/installer | php
- - php composer.phar install --prefer-source --no-interaction
-
-script:
- - ./vendor/bin/phpunit
diff --git a/README.md b/README.md
index e5f4f93..5e2e293 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,7 @@ SimpleRouter::get('/', function() {
### Support the project
-If you like simple-router and wish to see the continued development and maintenance of the project,
-please consider showing your support by buying me a coffee. Supporters will be listed under the credits section of this documentation.
+If you like simple-router and wish to see the continued development and maintenance of the project, please consider showing your support by buying me a coffee. Supporters will be listed under the credits section of this documentation.
You can donate any amount of your choice by [clicking here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NNX4D2RUSALCN).
@@ -33,6 +32,7 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Helper functions](#helper-functions)
- [Routes](#routes)
- [Basic routing](#basic-routing)
+ - [Class hinting](#class-hinting)
- [Available methods](#available-methods)
- [Multiple HTTP-verbs](#multiple-http-verbs)
- [Route parameters](#route-parameters)
@@ -51,9 +51,6 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Partial groups](#partial-groups)
- [Form Method Spoofing](#form-method-spoofing)
- [Accessing The Current Route](#accessing-the-current-route)
- - [Dependency injection](#dependency-injection)
- - [Enabling dependency injection](#enabling-dependency-injection)
- - [More reading](#more-reading)
- [Other examples](#other-examples)
- [CSRF-protection](#csrf-protection)
- [Adding CSRF-verifier](#adding-csrf-verifier)
@@ -85,10 +82,13 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Registering new event](#registering-new-event)
- [Custom EventHandlers](#custom-eventhandlers)
- [Advanced](#advanced)
+ - [Disable multiple route rendering](#disable-multiple-route-rendering)
- [Url rewriting](#url-rewriting)
- [Changing current route](#changing-current-route)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Adding routes manually](#adding-routes-manually)
+ - [Custom class-loader](#custom-class-loader)
+ - [Integrating with php-di](#Integrating-with-php-di)
- [Parameters](#parameters)
- [Extending](#extending)
- [Help and support](#help-and-support)
@@ -123,7 +123,7 @@ composer require pecee/simple-router
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
-We've included a simple demo project for the router which can be found in the `demo-project` folder. This project should give you a basic understanding of how to setup and use simple-php-router project.
+We've included a simple demo project for the router which can be found [here](https://github.com/skipperbent/simple-router-demo). This project should give you a basic understanding of how to setup and use simple-php-router project.
Please note that the demo-project only covers how to integrate the `simple-php-router` in a project without an existing framework. If you are using a framework in your project, the implementation might vary.
@@ -250,6 +250,7 @@ To add `favicon.ico` to the IIS ignore-list, add the following line to the `
```
@@ -257,6 +258,7 @@ You can also make one exception for files with some extensions:
If you are using `$_SERVER['ORIG_PATH_INFO']`, you will get `\index.php\` as part of the returned value.
**Example:**
+
```
/index.php/test/mypage.php
```
@@ -298,8 +300,6 @@ We recommend that you add these helper functions to your project. These will all
To implement the functions below, simply copy the code to a new file and require the file before initializing the router or copy the `helpers.php` we've included in this library.
```php
-where('name', '[A-Za-z]+');
+})->where([ 'name' => '[A-Za-z]+' ]);
SimpleRouter::get('/user/{id}', function ($id) {
// ... do stuff
-})->where('id', '[0-9]+');
+})->where([ 'id' => '[0-9]+' ]);
SimpleRouter::get('/user/{id}/{name}', function ($id, $name) {
@@ -522,10 +530,12 @@ SimpleRouter::all('/ajax/abc/123', function($param1, $param2) {
### Custom regex for matching parameters
-By default simple-php-router uses the `\w` regular expression when matching parameters.
+By default simple-php-router uses the `[\w\-]+` regular expression. It will match `A-Z`, `a-z`, `0-9`, `-` and `_` characters in 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.
+However, sometimes it can be necessary to add a custom regular expression to match more advanced characters like foreign letters `æ ø å` etc.
+
+You can test your custom regular expression by using on the site [Regex101.com](https://www.regex101.com).
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.
@@ -533,16 +543,16 @@ Instead of adding a custom regular expression to all your parameters, you can si
#### Example
-This example will ensure that all parameters use the `[\w\-]+` regular expression when parsing.
+This example will ensure that all parameters use the `[\w\-\æ\ø\å]+` (`a-z`, `A-Z`, `-`, `_`, `0-9`, `æ`, `ø`, `å`) regular expression when parsing.
```php
-SimpleRouter::get('/path/{parameter}', 'VideoController@home', ['defaultParameterRegex' => '[\w\-]+']);
+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::group(['defaultParameterRegex' => '[\w\-\æ\ø\å]+'], function() {
SimpleRouter::get('/path/{parameter}', 'VideoController@home');
@@ -648,6 +658,7 @@ SimpleRouter::group(['prefix' => '/admin'], function () {
## Partial groups
Partial router groups has the same benefits as a normal group, but supports parameters and are only rendered once the url has matched.
+Partial groups will render once a part of the url has matched.
This can be extremely useful in situations, where you only want special routes to be added, when a certain criteria or logic has been met.
@@ -656,11 +667,11 @@ This can be extremely useful in situations, where you only want special routes t
**Example:**
```php
-SimpleRouter::partialGroup('/admin/{applicationId}', function ($applicationId) {
+SimpleRouter::partialGroup('/lang/{language}', function ($language) {
- SimpleRouter::get('/', function($applicationId) {
+ SimpleRouter::get('/', function($language) {
- // Matches The "/admin/applicationId" URL
+ // Matches The "/lang/da" URL
});
@@ -685,88 +696,6 @@ SimpleRouter::request()->getLoadedRoute();
request()->getLoadedRoute();
```
-## Dependency injection
-
-simple-router supports dependency injection using the [`php-di`](http://php-di.org/) library.
-
-Dependency injection allows the framework to automatically "inject" (load) classes added as parameters. This can simplify your code, as you can avoid creating new instances of objects you are using often in your `Controllers` etc.
-
-Here's a basic example of a controller class using dependency injection:
-
-```php
-namespace Demo\Controllers;
-
-class DefaultController {
-
- public function login(User $user): string
- {
- // ...
- }
-
-}
-```
-
-The example above will automatically create a new instance of the `User` from the `$user` parameter. This means that the `$user` class contains a new instance of the `User` class and we won't need to create a new instance our self.
-
-**WARNING:** dependency injection can have some negative impact in performance. If you experience any performance issues, we recommend disabling this functionality.
-
-### Enabling dependency injection
-
-Dependency injection is disabled per default to avoid any performance issues.
-
-Before enabling dependency injection, we recommend that you read the [Container configuration](http://php-di.org/doc/container-configuration.html) section of the php-di documentation. This section covers how to configure php-di to different environments and speed-up the performance.
-
-#### Enabling for development environment
-
-The example below should ONLY be used on a development environment.
-
-```php
-// Create our new php-di container
-$container = (new \DI\ContainerBuilder())
- ->useAutowiring(true)
- ->build();
-
-// Add our container to simple-router and enable dependency injection
-SimpleRouter::enableDependencyInjection($container);
-```
-
-Please check the [More reading](#more-reading) section of the documentation for useful php-di links and tutorials.
-
-#### Enabling for production environment
-
-The example below compiles the injections, which can help speed up performance.
-
-**Note:** You should change the `$cacheDir` to a cache-storage within your project.
-
-```php
-// Cache directory
-$cacheDir = sys_get_temp_dir('simple-router');
-
-// Create our new php-di container
-$container = (new \DI\ContainerBuilder())
- ->enableCompilation($cacheDir)
- ->writeProxiesToFile(true, $cacheDir . '/proxies')
- ->useAutowiring(true)
- ->build();
-
-// Add our container to simple-router and enable dependency injection
-SimpleRouter::enableDependencyInjection($container);
-```
-
-Please check the [More reading](#more-reading) section of the documentation for useful php-di links and tutorials.
-
-### More reading
-
-For more information about dependency injection, configuration and settings - we recommend that you check the php-di documentation or some of the useful links we've gathered below.
-
-#### Useful links
-
-- [php-di documentation](http://php-di.org/doc/)
-- [Understanding dependency injection](http://php-di.org/doc/understanding-di.html)
-- [Best practices guide](http://php-di.org/doc/best-practices.html)
-- [Configuring the container](http://php-di.org/doc/container-configuration.html)
-- [Definitions](http://php-di.org/doc/definition.html)
-
## Other examples
You can find many more examples in the `routes.php` example-file below:
@@ -783,12 +712,17 @@ SimpleRouter::group(['middleware' => \Demo\Middlewares\Site::class, 'exceptionHa
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show', ['where' => ['id' => '[0-9]+']]);
+ /**
+ * Class hinting is supported too
+ */
+
+ SimpleRouter::get('/answers/{id}', [ControllerAnswers::class, 'show'], ['where' => ['id' => '[0-9]+']]);
/**
* Restful resource (see IRestController interface for available methods)
*/
- SimpleRouter::resource('/rest', ControllerRessource::class);
+ SimpleRouter::resource('/rest', ControllerResource::class);
/**
@@ -809,7 +743,6 @@ SimpleRouter::group(['middleware' => \Demo\Middlewares\Site::class, 'exceptionHa
});
SimpleRouter::get('/page/404', 'ControllerPage@notFound', ['as' => 'page.notfound']);
-
```
---
@@ -1429,6 +1362,12 @@ class DatabaseDebugHandler implements IEventHandler
# Advanced
+## Disable multiple route rendering
+
+By default the router will try to execute all routes that matches a given url. To stop the router from executing any further routes any method can return a value.
+
+This behavior can be easily disabled by setting `SimpleRouter::enableMultiRouteRendering(false)` in your `routes.php` file. This is the same behavior as version 3 and below.
+
## Url rewriting
### Changing current route
@@ -1480,7 +1419,7 @@ class CustomRouterRules implement IRouterBootManager
// If the current url matches the rewrite url, we use our custom route
- if($request->getUrl()->getPath() === $url) {
+ if($request->getUrl()->contains($url)) {
$request->setRewriteUrl($rule);
}
}
@@ -1528,6 +1467,119 @@ $route->setPrefix('v1');
$router->addRoute($route);
```
+## Custom class loader
+
+You can easily extend simple-router to support custom injection frameworks like php-di by taking advantage of the ability to add your custom class-loader.
+
+Class-loaders must inherit the `IClassLoader` interface.
+
+**Example:**
+
+```php
+class MyCustomClassLoader implements IClassLoader
+{
+ /**
+ * Load class
+ *
+ * @param string $class
+ * @return object
+ * @throws NotFoundHttpException
+ */
+ public function loadClass(string $class)
+ {
+ if (\class_exists($class) === false) {
+ throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
+ }
+
+ return new $class();
+ }
+
+ /**
+ * Load closure
+ *
+ * @param Callable $closure
+ * @param array $parameters
+ * @return mixed
+ */
+ public function loadClosure(Callable $closure, array $parameters)
+ {
+ return \call_user_func_array($closure, $parameters);
+ }
+
+}
+```
+
+Next, we need to configure our `routes.php` so the router uses our `MyCustomClassLoader` class for loading classes. This can be done by adding the following line to your `routes.php` file.
+
+```php
+SimpleRouter::setCustomClassLoader(new MyCustomClassLoader());
+```
+
+### Integrating with php-di
+
+php-di support was discontinued by version 4.3, however you can easily add it again by creating your own class-loader like the example below:
+
+```php
+class MyCustomClassLoader implements IClassLoader
+{
+
+ protected $container;
+
+ public function __construct()
+ {
+ // Create our new php-di container
+ $container = (new \DI\ContainerBuilder())
+ ->useAutowiring(true)
+ ->build();
+ }
+
+ /**
+ * Load class
+ *
+ * @param string $class
+ * @return object
+ * @throws NotFoundHttpException
+ */
+ public function loadClass(string $class)
+ {
+ if (class_exists($class) === false) {
+ throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
+ }
+
+ if ($this->container !== null) {
+ try {
+ return $this->container->get($class);
+ } catch (\Exception $e) {
+ throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
+ }
+ }
+
+ return new $class();
+ }
+
+ /**
+ * Load closure
+ *
+ * @param Callable $closure
+ * @param array $parameters
+ * @return mixed
+ */
+ public function loadClosure(Callable $closure, array $parameters)
+ {
+ if ($this->container !== null) {
+ try {
+ return $this->container->call($closure, $parameters);
+ } catch (\Exception $e) {
+ throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
+ }
+ }
+
+ return \call_user_func_array($closure, $parameters);
+ }
+
+}
+```
+
## Parameters
This section contains advanced tips & tricks on extending the usage for parameters.
@@ -1854,4 +1906,4 @@ 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.
+SOFTWARE.
\ No newline at end of file
diff --git a/composer.json b/composer.json
index 5d285cd..7b18724 100644
--- a/composer.json
+++ b/composer.json
@@ -28,13 +28,17 @@
],
"require": {
"php": ">=7.1",
- "ext-json": "*",
- "php-di/php-di": "^6.0"
+ "ext-json": "*"
},
"require-dev": {
- "phpunit/phpunit": "^6.0",
+ "phpunit/phpunit": "^7",
"mockery/mockery": "^1"
},
+ "scripts": {
+ "test": [
+ "phpunit tests"
+ ]
+ },
"autoload": {
"psr-4": {
"Pecee\\": "src/Pecee/"
diff --git a/helpers.php b/helpers.php
index b404858..81d836f 100644
--- a/helpers.php
+++ b/helpers.php
@@ -47,7 +47,7 @@ function request(): Request
/**
* Get input class
* @param string|null $index Parameter index name
- * @param string|null $defaultValue Default return value
+ * @param string|mixed|null $defaultValue Default return value
* @param array ...$methods Default methods
* @return \Pecee\Http\Input\InputHandler|array|string|null
*/
diff --git a/phpunit.xml b/phpunit.xml
index 6e8f0c6..49b5e9e 100644
--- a/phpunit.xml
+++ b/phpunit.xml
@@ -9,15 +9,15 @@
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
- stopOnFailure="false"
- syntaxCheck="false">
+ stopOnFailure="false">
tests/Pecee/SimpleRouter/
-
+
src
diff --git a/src/Pecee/Http/Input/IInputItem.php b/src/Pecee/Http/Input/IInputItem.php
index cc5a4e0..0c851c8 100644
--- a/src/Pecee/Http/Input/IInputItem.php
+++ b/src/Pecee/Http/Input/IInputItem.php
@@ -13,9 +13,9 @@ interface IInputItem
public function setName(string $name): self;
- public function getValue(): ?string;
+ public function getValue();
- public function setValue(string $value): self;
+ public function setValue($value): self;
public function __toString(): string;
diff --git a/src/Pecee/Http/Input/InputFile.php b/src/Pecee/Http/Input/InputFile.php
index 2919187..c2c345f 100644
--- a/src/Pecee/Http/Input/InputFile.php
+++ b/src/Pecee/Http/Input/InputFile.php
@@ -261,16 +261,16 @@ class InputFile implements IInputItem
return $this->getTmpName();
}
- public function getValue(): ?string
+ public function getValue()
{
return $this->getFilename();
}
/**
- * @param string $value
+ * @param mixed $value
* @return static
*/
- public function setValue(string $value): IInputItem
+ public function setValue($value): IInputItem
{
$this->filename = $value;
diff --git a/src/Pecee/Http/Input/InputHandler.php b/src/Pecee/Http/Input/InputHandler.php
index f05bf10..13bfe5c 100644
--- a/src/Pecee/Http/Input/InputHandler.php
+++ b/src/Pecee/Http/Input/InputHandler.php
@@ -27,6 +27,24 @@ class InputHandler
*/
protected $request;
+ /**
+ * Original post variables
+ * @var array
+ */
+ protected $originalPost = [];
+
+ /**
+ * Original get/params variables
+ * @var array
+ */
+ protected $originalParams = [];
+
+ /**
+ * Get original file variables
+ * @var array
+ */
+ protected $originalFile = [];
+
/**
* Input constructor.
* @param Request $request
@@ -46,38 +64,59 @@ class InputHandler
{
/* Parse get requests */
if (\count($_GET) !== 0) {
- $this->get = $this->parseInputItem($_GET);
+ $this->originalParams = $_GET;
+ $this->get = $this->parseInputItem($this->originalParams);
}
/* Parse post requests */
- $postVars = $_POST;
+ $this->originalPost = $_POST;
- if (\in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
- parse_str(file_get_contents('php://input'), $postVars);
+ if ($this->request->isPostBack() === true) {
+
+ $contents = file_get_contents('php://input');
+
+ // Append any PHP-input json
+ if (strpos(trim($contents), '{') === 0) {
+ $post = json_decode($contents, true);
+
+ if ($post !== false) {
+ $this->originalPost += $post;
+ }
+ }
}
- if (\count($postVars) !== 0) {
- $this->post = $this->parseInputItem($postVars);
+ if (\count($this->originalPost) !== 0) {
+ $this->post = $this->parseInputItem($this->originalPost);
}
/* Parse get requests */
if (\count($_FILES) !== 0) {
- $this->file = $this->parseFiles();
+ $this->originalFile = $_FILES;
+ $this->file = $this->parseFiles($this->originalFile);
}
}
/**
+ * @param array $files Array with files to parse
+ * @param string|null $parentKey Key from parent (used when parsing nested array).
* @return array
*/
- public function parseFiles(): array
+ public function parseFiles(array $files, ?string $parentKey = null): array
{
$list = [];
- foreach ((array)$_FILES as $key => $value) {
+ foreach ($files as $key => $value) {
+
+ // Parse multi dept file array
+ if(isset($value['name']) === false && \is_array($value) === true) {
+ $list[$key] = $this->parseFiles($value, $key);
+ continue;
+ }
// Handle array input
if (\is_array($value['name']) === false) {
- $values['index'] = $key;
+ $values['index'] = $parentKey ?? $key;
+
try {
$list[$key] = InputFile::createFromArray($values + $value);
} catch (InvalidArgumentException $e) {
@@ -171,14 +210,11 @@ class InputHandler
foreach ($array as $key => $value) {
// Handle array input
- if (\is_array($value) === false) {
- $list[$key] = new InputItem($key, $value);
- continue;
+ if (\is_array($value) === true) {
+ $value = $this->parseInputItem($value);
}
- $output = $this->parseInputItem($value);
-
- $list[$key] = $output;
+ $list[$key] = new InputItem($key, $value);
}
return $list;
@@ -195,11 +231,11 @@ class InputHandler
{
$element = null;
- if (\count($methods) === 0 || \in_array('get', $methods, true) === true) {
+ if (\count($methods) === 0 || \in_array(Request::REQUEST_TYPE_GET, $methods, true) === true) {
$element = $this->get($index);
}
- if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array('post', $methods, true) === true)) {
+ if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array(Request::REQUEST_TYPE_POST, $methods, true) === true)) {
$element = $this->post($index);
}
@@ -210,31 +246,46 @@ class InputHandler
return $element;
}
+ protected function getValueFromArray(array $array): array
+ {
+ $output = [];
+ /* @var $item InputItem */
+ foreach ($array as $key => $item) {
+
+ if ($item instanceof IInputItem) {
+ $item = $item->getValue();
+ }
+
+ $output[$key] = \is_array($item) ? $this->getValueFromArray($item) : $item;
+ }
+
+ return $output;
+ }
+
/**
* Get input element value matching index
*
* @param string $index
- * @param string|null $defaultValue
+ * @param string|mixed|null $defaultValue
* @param array ...$methods
* @return string|array
*/
- public function value(string $index, ?string $defaultValue = null, ...$methods)
+ public function value(string $index, $defaultValue = null, ...$methods)
{
$input = $this->find($index, ...$methods);
- $output = [];
+ if ($input instanceof IInputItem) {
+ $input = $input->getValue();
+ }
/* Handle collection */
if (\is_array($input) === true) {
- /* @var $item InputItem */
- foreach ($input as $item) {
- $output[] = $item->getValue();
- }
+ $output = $this->getValueFromArray($input);
return (\count($output) === 0) ? $defaultValue : $output;
}
- return ($input === null || ($input !== null && trim($input->getValue()) === '')) ? $defaultValue : $input->getValue();
+ return ($input === null || (\is_string($input) && trim($input) === '')) ? $defaultValue : $input;
}
/**
@@ -292,24 +343,16 @@ class InputHandler
*/
public function all(array $filter = []): array
{
- $output = $_GET;
+ $output = $this->originalParams + $this->originalPost + $this->originalFile;
+ $output = (\count($filter) > 0) ? \array_intersect_key($output, \array_flip($filter)) : $output;
- if ($this->request->getMethod() === 'post') {
-
- // Append POST data
- $output += $_POST;
- $contents = file_get_contents('php://input');
-
- // Append any PHP-input json
- if (strpos(trim($contents), '{') === 0) {
- $post = json_decode($contents, true);
- if ($post !== false) {
- $output += $post;
- }
+ foreach ($filter as $filterKey) {
+ if (array_key_exists($filterKey, $output) === false) {
+ $output[$filterKey] = null;
}
}
- return (\count($filter) > 0) ? array_intersect_key($output, array_flip($filter)) : $output;
+ return $output;
}
/**
@@ -345,4 +388,67 @@ class InputHandler
$this->file[$key] = $item;
}
+ /**
+ * Get original post variables
+ * @return array
+ */
+ public function getOriginalPost(): array
+ {
+ return $this->originalPost;
+ }
+
+ /**
+ * Set original post variables
+ * @param array $post
+ * @return static $this
+ */
+ public function setOriginalPost(array $post): self
+ {
+ $this->originalPost = $post;
+
+ return $this;
+ }
+
+ /**
+ * Get original get variables
+ * @return array
+ */
+ public function getOriginalParams(): array
+ {
+ return $this->originalParams;
+ }
+
+ /**
+ * Set original get-variables
+ * @param array $params
+ * @return static $this
+ */
+ public function setOriginalParams(array $params): self
+ {
+ $this->originalParams = $params;
+
+ return $this;
+ }
+
+ /**
+ * Get original file variables
+ * @return array
+ */
+ public function getOriginalFile(): array
+ {
+ return $this->originalFile;
+ }
+
+ /**
+ * Set original file posts variables
+ * @param array $file
+ * @return static $this
+ */
+ public function setOriginalFile(array $file): self
+ {
+ $this->originalFile = $file;
+
+ return $this;
+ }
+
}
\ No newline at end of file
diff --git a/src/Pecee/Http/Input/InputItem.php b/src/Pecee/Http/Input/InputItem.php
index 6c677b8..2322bd3 100644
--- a/src/Pecee/Http/Input/InputItem.php
+++ b/src/Pecee/Http/Input/InputItem.php
@@ -2,13 +2,13 @@
namespace Pecee\Http\Input;
-class InputItem implements IInputItem
+class InputItem implements IInputItem, \IteratorAggregate
{
public $index;
public $name;
public $value;
- public function __construct(string $index, ?string $value = null)
+ public function __construct(string $index, $value = null)
{
$this->index = $index;
$this->value = $value;
@@ -53,19 +53,19 @@ class InputItem implements IInputItem
}
/**
- * @return string
+ * @return mixed
*/
- public function getValue(): ?string
+ public function getValue()
{
return $this->value;
}
/**
* Set input value
- * @param string $value
+ * @param mixed $value
* @return static
*/
- public function setValue(string $value): IInputItem
+ public function setValue($value): IInputItem
{
$this->value = $value;
@@ -74,7 +74,12 @@ class InputItem implements IInputItem
public function __toString(): string
{
- return (string)$this->value;
+ $value = $this->getValue();
+ return (\is_array($value) === true) ? json_encode($value) : $value;
}
+ public function getIterator(): \ArrayIterator
+ {
+ return new \ArrayIterator($this->getValue());
+ }
}
\ No newline at end of file
diff --git a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php
index da1ce3e..392bcf9 100644
--- a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php
+++ b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php
@@ -17,7 +17,6 @@ class BaseCsrfVerifier implements IMiddleware
/**
* BaseCsrfVerifier constructor.
- * @throws \Pecee\Http\Security\Exceptions\SecurityException
*/
public function __construct()
{
@@ -64,13 +63,12 @@ class BaseCsrfVerifier implements IMiddleware
*/
public function handle(Request $request): void
{
-
- if ($this->skip($request) === false && \in_array($request->getMethod(), ['post', 'put', 'delete'], true) === true) {
+ if ($this->skip($request) === false && $request->isPostBack() === true) {
$token = $request->getInputHandler()->value(
static::POST_KEY,
$request->getHeader(static::HEADER_KEY),
- 'post'
+ Request::$requestTypesPost
);
if ($this->tokenProvider->validate((string)$token) === false) {
@@ -81,7 +79,6 @@ class BaseCsrfVerifier implements IMiddleware
// Refresh existing token
$this->tokenProvider->refresh();
-
}
public function getTokenProvider(): ITokenProvider
diff --git a/src/Pecee/Http/Request.php b/src/Pecee/Http/Request.php
index 31dc0ae..fddb573 100644
--- a/src/Pecee/Http/Request.php
+++ b/src/Pecee/Http/Request.php
@@ -4,12 +4,52 @@ namespace Pecee\Http;
use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Input\InputHandler;
+use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter;
class Request
{
+ public const REQUEST_TYPE_GET = 'get';
+ public const REQUEST_TYPE_POST = 'post';
+ public const REQUEST_TYPE_PUT = 'put';
+ public const REQUEST_TYPE_PATCH = 'patch';
+ public const REQUEST_TYPE_OPTIONS = 'options';
+ public const REQUEST_TYPE_DELETE = 'delete';
+ public const REQUEST_TYPE_HEAD = 'head';
+
+ public const CONTENT_TYPE_JSON = 'application/json';
+ public const CONTENT_TYPE_FORM_DATA = 'multipart/form-data';
+ public const CONTENT_TYPE_X_FORM_ENCODED = 'application/x-www-form-urlencoded';
+
+ public const FORCE_METHOD_KEY = '_method';
+
+ /**
+ * All request-types
+ * @var string[]
+ */
+ public static $requestTypes = [
+ self::REQUEST_TYPE_GET,
+ self::REQUEST_TYPE_POST,
+ self::REQUEST_TYPE_PUT,
+ self::REQUEST_TYPE_PATCH,
+ self::REQUEST_TYPE_OPTIONS,
+ self::REQUEST_TYPE_DELETE,
+ self::REQUEST_TYPE_HEAD,
+ ];
+
+ /**
+ * Post request-types.
+ * @var string[]
+ */
+ public static $requestTypesPost = [
+ self::REQUEST_TYPE_POST,
+ self::REQUEST_TYPE_PUT,
+ self::REQUEST_TYPE_PATCH,
+ self::REQUEST_TYPE_DELETE,
+ ];
+
/**
* Additional data
*
@@ -23,6 +63,12 @@ class Request
*/
protected $headers = [];
+ /**
+ * Request ContentType
+ * @var string
+ */
+ protected $contentType;
+
/**
* Request host
* @var string
@@ -77,17 +123,16 @@ class Request
{
foreach ($_SERVER as $key => $value) {
$this->headers[strtolower($key)] = $value;
- $this->headers[strtolower(str_replace('_', '-', $key))] = $value;
+ $this->headers[str_replace('_', '-', strtolower($key))] = $value;
}
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
- $this->setUrl(new Url($this->getHeader('unencoded-url', $this->getHeader('request-uri'))));
-
- $this->method = strtolower($this->getHeader('request-method'));
+ $this->setUrl(new Url($this->getFirstHeader(['unencoded-url', 'request-uri'])));
+ $this->setContentType((string)$this->getHeader('content-type'));
+ $this->setMethod((string)($_POST[static::FORCE_METHOD_KEY] ?? $this->getHeader('request-method')));
$this->inputHandler = new InputHandler($this);
- $this->method = strtolower($this->inputHandler->value('_method', $this->getHeader('request-method')));
}
public function isSecure(): bool
@@ -147,6 +192,15 @@ class Request
return $this->getHeader('php-auth-pw');
}
+ /**
+ * Get the csrf token
+ * @return string|null
+ */
+ public function getCsrfToken(): ?string
+ {
+ return $this->getHeader(BaseCsrfVerifier::HEADER_KEY);
+ }
+
/**
* Get all headers
* @return array
@@ -158,19 +212,23 @@ class Request
/**
* Get id address
+ * If $safe is false, this function will detect Proxys. But the user can edit this header to whatever he wants!
+ * https://stackoverflow.com/questions/3003145/how-to-get-the-client-ip-address-in-php#comment-25086804
+ * @param bool $safeMode When enabled, only safe non-spoofable headers will be returned. Note this can cause issues when using proxy.
* @return string|null
*/
- public function getIp(): ?string
+ public function getIp(bool $safeMode = false): ?string
{
- if ($this->getHeader('http-cf-connecting-ip') !== null) {
- return $this->getHeader('http-cf-connecting-ip');
+ $headers = ['remote-addr'];
+ if($safeMode === false) {
+ $headers = array_merge($headers, [
+ 'http-cf-connecting-ip',
+ 'http-client-ip',
+ 'http-x-forwarded-for',
+ ]);
}
- if ($this->getHeader('http-x-forwarded-for') !== null) {
- return $this->getHeader('http-x-forwarded_for');
- }
-
- return $this->getHeader('remote-addr');
+ return $this->getFirstHeader($headers);
}
/**
@@ -205,14 +263,72 @@ class Request
/**
* Get header value by name
*
- * @param string $name
- * @param string|null $defaultValue
+ * @param string $name Name of the header.
+ * @param string|null $defaultValue Value to be returned if header is not found.
+ * @param bool $tryParse When enabled the method will try to find the header from both from client (http) and server-side variants, if the header is not found.
*
* @return string|null
*/
- public function getHeader($name, $defaultValue = null): ?string
+ public function getHeader(string $name, $defaultValue = null, $tryParse = true): ?string
{
- return $this->headers[strtolower($name)] ?? $defaultValue;
+ $name = strtolower($name);
+ $header = $this->headers[$name] ?? null;
+
+ if ($tryParse === true && $header === null) {
+ if (strpos($name, 'http-') === 0) {
+ // Trying to find client header variant which was not found, searching for header variant without http- prefix.
+ $header = $this->headers[str_replace('http-', '', $name)] ?? null;
+ } else {
+ // Trying to find server variant which was not found, searching for client variant with http- prefix.
+ $header = $this->headers['http-' . $name] ?? null;
+ }
+ }
+
+ return $header ?? $defaultValue;
+ }
+
+ /**
+ * Will try to find first header from list of headers.
+ *
+ * @param array $headers
+ * @param mixed|null $defaultValue
+ * @return mixed|null
+ */
+ public function getFirstHeader(array $headers, $defaultValue = null)
+ {
+ foreach($headers as $header) {
+ $header = $this->getHeader($header);
+ if($header !== null) {
+ return $header;
+ }
+ }
+
+ return $defaultValue;
+ }
+
+ /**
+ * Get request content-type
+ * @return string|null
+ */
+ public function getContentType(): ?string
+ {
+ return $this->contentType;
+ }
+
+ /**
+ * Set request content-type
+ * @param string $contentType
+ * @return $this
+ */
+ protected function setContentType(string $contentType): self
+ {
+ if(strpos($contentType, ';') > 0) {
+ $this->contentType = strtolower(substr($contentType, 0, strpos($contentType, ';')));
+ } else {
+ $this->contentType = strtolower($contentType);
+ }
+
+ return $this;
}
/**
@@ -231,7 +347,7 @@ class Request
*
* @return bool
*/
- public function isFormatAccepted($format): bool
+ public function isFormatAccepted(string $format): bool
{
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) !== false);
}
@@ -246,6 +362,16 @@ class Request
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
}
+ /**
+ * Returns true when request-method is type that could contain data in the page body.
+ *
+ * @return bool
+ */
+ public function isPostBack(): bool
+ {
+ return \in_array($this->getMethod(), static::$requestTypesPost, true);
+ }
+
/**
* Get accept formats
* @return array
@@ -371,7 +497,6 @@ class Request
public function setLoadedRoutes(array $routes): self
{
$this->loadedRoutes = $routes;
-
return $this;
}
@@ -384,7 +509,6 @@ class Request
public function addLoadedRoute(ILoadableRoute $route): self
{
$this->loadedRoutes[] = $route;
-
return $this;
}
@@ -407,11 +531,10 @@ class Request
public function setHasPendingRewrite(bool $boolean): self
{
$this->hasPendingRewrite = $boolean;
-
return $this;
}
- public function __isset($name)
+ public function __isset($name): bool
{
return array_key_exists($name, $this->data) === true;
}
@@ -426,4 +549,4 @@ class Request
return $this->data[$name] ?? null;
}
-}
+}
\ No newline at end of file
diff --git a/src/Pecee/Http/Response.php b/src/Pecee/Http/Response.php
index 2e199f5..e7a7da9 100644
--- a/src/Pecee/Http/Response.php
+++ b/src/Pecee/Http/Response.php
@@ -30,7 +30,7 @@ class Response
* Redirect the response
*
* @param string $url
- * @param int $httpCode
+ * @param ?int $httpCode
*/
public function redirect(string $url, ?int $httpCode = null): void
{
@@ -86,7 +86,7 @@ class Response
/**
* Json encode
* @param array|\JsonSerializable $value
- * @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
+ * @param ?int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param int $dept JSON debt.
* @throws InvalidArgumentException
*/
diff --git a/src/Pecee/Http/Security/CookieTokenProvider.php b/src/Pecee/Http/Security/CookieTokenProvider.php
index cb6da8f..35f1021 100644
--- a/src/Pecee/Http/Security/CookieTokenProvider.php
+++ b/src/Pecee/Http/Security/CookieTokenProvider.php
@@ -17,7 +17,7 @@ class CookieTokenProvider implements ITokenProvider
*/
public function __construct()
{
- $this->token = $this->getToken();
+ $this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
if ($this->token === null) {
$this->token = $this->generateToken();
@@ -63,7 +63,7 @@ class CookieTokenProvider implements ITokenProvider
public function setToken(string $token): void
{
$this->token = $token;
- setcookie(static::CSRF_KEY, $token, (time() + 60) * $this->cookieTimeoutMinutes, '/', ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
+ setcookie(static::CSRF_KEY, $token, time() + (60 * $this->cookieTimeoutMinutes), '/', ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
}
/**
@@ -73,8 +73,6 @@ class CookieTokenProvider implements ITokenProvider
*/
public function getToken(?string $defaultValue = null): ?string
{
- $this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
-
return $this->token ?? $defaultValue;
}
diff --git a/src/Pecee/Http/Url.php b/src/Pecee/Http/Url.php
index 5f34525..256e4a5 100644
--- a/src/Pecee/Http/Url.php
+++ b/src/Pecee/Http/Url.php
@@ -20,7 +20,7 @@ class Url implements \JsonSerializable
/**
* Url constructor.
*
- * @param string $url
+ * @param ?string $url
* @throws MalformedUrlException
*/
public function __construct(?string $url)
@@ -371,7 +371,7 @@ class Url implements \JsonSerializable
*/
public function getParam(string $name, ?string $defaultValue = null): ?string
{
- return isset($this->getParams()[$name]) ?? $defaultValue;
+ return (isset($this->getParams()[$name]) === true) ? $this->getParams()[$name] : $defaultValue;
}
/**
@@ -385,7 +385,7 @@ class Url implements \JsonSerializable
{
$encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u',
- function ($matches) {
+ static function ($matches) {
return urlencode($matches[0]);
},
$url
@@ -412,7 +412,7 @@ class Url implements \JsonSerializable
if (\count($getParams) !== 0) {
if ($includeEmpty === false) {
- $getParams = array_filter($getParams, function ($item) {
+ $getParams = array_filter($getParams, static function ($item) {
return (trim($item) !== '');
});
}
diff --git a/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php b/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php
index caea1a5..027028e 100644
--- a/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php
+++ b/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php
@@ -2,44 +2,21 @@
namespace Pecee\SimpleRouter\ClassLoader;
-use DI\Container;
-use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
+use Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException;
class ClassLoader implements IClassLoader
{
- /**
- * Dependency injection enabled
- * @var bool
- */
- protected $useDependencyInjection = false;
-
- /**
- * @var Container|null
- */
- protected $container;
-
/**
* Load class
*
* @param string $class
- * @return mixed
- * @throws NotFoundHttpException
+ * @return object
+ * @throws ClassNotFoundHttpException
*/
public function loadClass(string $class)
{
if (class_exists($class) === false) {
- throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
- }
-
- if ($this->useDependencyInjection === true) {
- $container = $this->getContainer();
- if ($container !== null) {
- try {
- return $container->get($class);
- } catch (\Exception $e) {
- throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
- }
- }
+ throw new ClassNotFoundHttpException($class, null, sprintf('Class "%s" does not exist', $class), 404, null);
}
return new $class();
@@ -48,71 +25,13 @@ class ClassLoader implements IClassLoader
/**
* Load closure
*
- * @param \Closure $closure
+ * @param Callable $closure
* @param array $parameters
* @return mixed
- * @throws NotFoundHttpException
*/
- public function loadClosure(\Closure $closure, array $parameters)
+ public function loadClosure(Callable $closure, array $parameters)
{
- if ($this->useDependencyInjection === true) {
- $container = $this->getContainer();
- if ($container !== null) {
- try {
- return $container->call($closure, $parameters);
- } catch (\Exception $e) {
- throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
- }
- }
- }
-
return \call_user_func_array($closure, $parameters);
}
- /**
- * Get dependency injector container.
- *
- * @return Container|null
- */
- public function getContainer(): ?Container
- {
- return $this->container;
- }
-
- /**
- * Set the dependency-injector container.
- *
- * @param Container $container
- * @return ClassLoader
- */
- public function setContainer(Container $container): self
- {
- $this->container = $container;
-
- return $this;
- }
-
- /**
- * Enable or disable dependency injection.
- *
- * @param bool $enabled
- * @return static
- */
- public function useDependencyInjection(bool $enabled): self
- {
- $this->useDependencyInjection = $enabled;
-
- return $this;
- }
-
- /**
- * Return true if dependency injection is enabled.
- *
- * @return bool
- */
- public function isDependencyInjectionEnabled(): bool
- {
- return $this->useDependencyInjection;
- }
-
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/ClassLoader/IClassLoader.php b/src/Pecee/SimpleRouter/ClassLoader/IClassLoader.php
index d978ac1..8eb8cd1 100644
--- a/src/Pecee/SimpleRouter/ClassLoader/IClassLoader.php
+++ b/src/Pecee/SimpleRouter/ClassLoader/IClassLoader.php
@@ -5,8 +5,20 @@ namespace Pecee\SimpleRouter\ClassLoader;
interface IClassLoader
{
+ /**
+ * Called when loading class
+ * @param string $class
+ * @return object
+ */
public function loadClass(string $class);
- public function loadClosure(\Closure $closure, array $parameters);
+ /**
+ * Called when loading method
+ *
+ * @param callable $closure
+ * @param array $parameters
+ * @return mixed
+ */
+ public function loadClosure(Callable $closure, array $parameters);
-}
\ No newline at end of file
+}
diff --git a/src/Pecee/SimpleRouter/Event/EventArgument.php b/src/Pecee/SimpleRouter/Event/EventArgument.php
index 3346ffe..092f9a0 100644
--- a/src/Pecee/SimpleRouter/Event/EventArgument.php
+++ b/src/Pecee/SimpleRouter/Event/EventArgument.php
@@ -74,7 +74,7 @@ class EventArgument implements IEventArgument
* @param string $name
* @return mixed
*/
- public function __get($name)
+ public function __get(string $name)
{
return $this->arguments[$name] ?? null;
}
@@ -83,7 +83,7 @@ class EventArgument implements IEventArgument
* @param string $name
* @return bool
*/
- public function __isset($name)
+ public function __isset(string $name): bool
{
return array_key_exists($name, $this->arguments);
}
@@ -93,7 +93,7 @@ class EventArgument implements IEventArgument
* @param mixed $value
* @throws \InvalidArgumentException
*/
- public function __set($name, $value)
+ public function __set(string $name, $value)
{
throw new \InvalidArgumentException('Not supported');
}
diff --git a/src/Pecee/SimpleRouter/Exceptions/ClassNotFoundHttpException.php b/src/Pecee/SimpleRouter/Exceptions/ClassNotFoundHttpException.php
new file mode 100644
index 0000000..09fed6a
--- /dev/null
+++ b/src/Pecee/SimpleRouter/Exceptions/ClassNotFoundHttpException.php
@@ -0,0 +1,38 @@
+class = $class;
+ $this->method = $method;
+ }
+
+ /**
+ * Get class name
+ * @return string
+ */
+ public function getClass(): string
+ {
+ return $this->class;
+ }
+
+ /**
+ * Get method
+ * @return string|null
+ */
+ public function getMethod(): ?string
+ {
+ return $this->method;
+ }
+
+}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php b/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php
index 690b275..fe4a954 100644
--- a/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php
+++ b/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php
@@ -16,7 +16,7 @@ class DebugEventHandler implements IEventHandler
public function __construct()
{
- $this->callback = function (EventArgument $argument) {
+ $this->callback = static function (EventArgument $argument) {
// todo: log in database
};
}
diff --git a/src/Pecee/SimpleRouter/Handlers/EventHandler.php b/src/Pecee/SimpleRouter/Handlers/EventHandler.php
index 9ac42ec..70b37b3 100644
--- a/src/Pecee/SimpleRouter/Handlers/EventHandler.php
+++ b/src/Pecee/SimpleRouter/Handlers/EventHandler.php
@@ -143,7 +143,7 @@ class EventHandler implements IEventHandler
* Get events.
*
* @param string|null $name Filter events by name.
- * @param array ...$names Add multiple names...
+ * @param array|string ...$names Add multiple names...
* @return array
*/
public function getEvents(?string $name, ...$names): array
diff --git a/src/Pecee/SimpleRouter/Route/IGroupRoute.php b/src/Pecee/SimpleRouter/Route/IGroupRoute.php
index 2c18d1d..ff26273 100644
--- a/src/Pecee/SimpleRouter/Route/IGroupRoute.php
+++ b/src/Pecee/SimpleRouter/Route/IGroupRoute.php
@@ -29,7 +29,7 @@ interface IGroupRoute extends IRoute
* @param array $handlers
* @return static
*/
- public function setExceptionHandlers(array $handlers);
+ public function setExceptionHandlers(array $handlers): self;
/**
* Get exception-handlers for group
@@ -59,7 +59,7 @@ interface IGroupRoute extends IRoute
* @param string $prefix
* @return static
*/
- public function setPrefix($prefix): self;
+ public function setPrefix(string $prefix): self;
/**
* Get prefix.
diff --git a/src/Pecee/SimpleRouter/Route/ILoadableRoute.php b/src/Pecee/SimpleRouter/Route/ILoadableRoute.php
index d0d7090..0e874e8 100644
--- a/src/Pecee/SimpleRouter/Route/ILoadableRoute.php
+++ b/src/Pecee/SimpleRouter/Route/ILoadableRoute.php
@@ -82,6 +82,6 @@ interface ILoadableRoute extends IRoute
* @param string $regex
* @return static
*/
- public function setMatch($regex): self;
+ public function setMatch(string $regex): self;
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Route/IRoute.php b/src/Pecee/SimpleRouter/Route/IRoute.php
index 4654e1f..4ac88db 100644
--- a/src/Pecee/SimpleRouter/Route/IRoute.php
+++ b/src/Pecee/SimpleRouter/Route/IRoute.php
@@ -10,11 +10,11 @@ interface IRoute
/**
* Method called to check if a domain matches
*
- * @param string $route
+ * @param string $url
* @param Request $request
* @return bool
*/
- public function matchRoute($route, Request $request): bool;
+ public function matchRoute(string $url, Request $request): bool;
/**
* Called when route is matched.
@@ -22,8 +22,8 @@ interface IRoute
*
* @param Request $request
* @param Router $router
- * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return string
+ * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
*/
public function renderRoute(Request $request, Router $router): ?string;
@@ -82,7 +82,7 @@ interface IRoute
/**
* Set callback
*
- * @param string $callback
+ * @param string|array|\Closure $callback
* @return static
*/
public function setCallback($callback): self;
@@ -129,7 +129,7 @@ interface IRoute
* @param string $namespace
* @return static
*/
- public function setDefaultNamespace($namespace): IRoute;
+ public function setDefaultNamespace(string $namespace): IRoute;
/**
* Get default namespace
@@ -196,7 +196,7 @@ interface IRoute
* @param string $middleware
* @return static
*/
- public function addMiddleware($middleware): self;
+ public function addMiddleware(string $middleware): self;
/**
* Set middlewares array
@@ -206,4 +206,18 @@ interface IRoute
*/
public function setMiddlewares(array $middlewares): self;
+ /**
+ * If enabled parameters containing null-value will not be passed along to the callback.
+ *
+ * @param bool $enabled
+ * @return static $this
+ */
+ public function setFilterEmptyParams(bool $enabled): self;
+
+ /**
+ * Status if filtering of empty params is enabled or disabled
+ * @return bool
+ */
+ public function getFilterEmptyParams(): bool;
+
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Route/LoadableRoute.php b/src/Pecee/SimpleRouter/Route/LoadableRoute.php
index 536c415..edf414e 100644
--- a/src/Pecee/SimpleRouter/Route/LoadableRoute.php
+++ b/src/Pecee/SimpleRouter/Route/LoadableRoute.php
@@ -60,7 +60,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return null;
}
- return ((bool)preg_match($this->regex, $request->getHost() . $url) !== false);
+ return ((bool)preg_match($this->regex, $url) !== false);
}
/**
@@ -183,7 +183,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $regex
* @return static
*/
- public function setMatch($regex): ILoadableRoute
+ public function setMatch(string $regex): ILoadableRoute
{
$this->regex = $regex;
@@ -229,15 +229,15 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
/**
* Merge with information from another route.
*
- * @param array $values
+ * @param array $settings
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, bool $merge = false): IRoute
+ public function setSettings(array $settings, bool $merge = false): IRoute
{
- if (isset($values['as']) === true) {
+ if (isset($settings['as']) === true) {
- $name = $values['as'];
+ $name = $settings['as'];
if ($this->name !== null && $merge !== false) {
$name .= '.' . $this->name;
@@ -246,11 +246,11 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
$this->setName($name);
}
- if (isset($values['prefix']) === true) {
- $this->prependUrl($values['prefix']);
+ if (isset($settings['prefix']) === true) {
+ $this->prependUrl($settings['prefix']);
}
- return parent::setSettings($values, $merge);
+ return parent::setSettings($settings, $merge);
}
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Route/Route.php b/src/Pecee/SimpleRouter/Route/Route.php
index 08b8622..72c96c6 100644
--- a/src/Pecee/SimpleRouter/Route/Route.php
+++ b/src/Pecee/SimpleRouter/Route/Route.php
@@ -4,31 +4,14 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
+use Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Router;
abstract class Route implements IRoute
{
protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
- protected const PARAMETERS_DEFAULT_REGEX = '[\w]+';
-
- public const REQUEST_TYPE_GET = 'get';
- public const REQUEST_TYPE_POST = 'post';
- public const REQUEST_TYPE_PUT = 'put';
- public const REQUEST_TYPE_PATCH = 'patch';
- public const REQUEST_TYPE_OPTIONS = 'options';
- public const REQUEST_TYPE_DELETE = 'delete';
- public const REQUEST_TYPE_HEAD = 'head';
-
- public static $requestTypes = [
- self::REQUEST_TYPE_GET,
- self::REQUEST_TYPE_POST,
- self::REQUEST_TYPE_PUT,
- self::REQUEST_TYPE_PATCH,
- self::REQUEST_TYPE_OPTIONS,
- self::REQUEST_TYPE_DELETE,
- self::REQUEST_TYPE_HEAD,
- ];
+ protected const PARAMETERS_DEFAULT_REGEX = '[\w-]+';
/**
* If enabled parameters containing null-value
@@ -85,7 +68,7 @@ abstract class Route implements IRoute
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
- $parameters = array_filter($parameters, function ($var) {
+ $parameters = array_filter($parameters, static function ($var) {
return ($var !== null);
});
}
@@ -95,28 +78,24 @@ abstract class Route implements IRoute
$router->debug('Executing callback');
/* When the callback is a function */
-
return $router->getClassLoader()->loadClosure($callback, $parameters);
}
- /* When the callback is a class + method */
- $controller = explode('@', $callback);
+ $controller = $this->getClass();
+ $method = $this->getMethod();
$namespace = $this->getNamespace();
-
- $className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
+ $className = ($namespace !== null && $controller[0] !== '\\') ? $namespace . '\\' . $controller : $controller;
$router->debug('Loading class %s', $className);
$class = $router->getClassLoader()->loadClass($className);
- if (\count($controller) === 1) {
+ if ($method === null) {
$controller[1] = '__invoke';
}
- $method = $controller[1];
-
if (method_exists($class, $method) === false) {
- throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
+ throw new ClassNotFoundHttpException($className, $method, sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404, null);
}
$router->debug('Executing callback');
@@ -124,7 +103,7 @@ abstract class Route implements IRoute
return \call_user_func_array([$class, $method], $parameters);
}
- protected function parseParameters($route, $url, $parameterRegex = null)
+ protected function parseParameters($route, $url, $parameterRegex = null): ?array
{
$regex = (strpos($route, $this->paramModifiers[0]) === false) ? null :
sprintf
@@ -144,7 +123,7 @@ abstract class Route implements IRoute
$urlRegex = preg_quote($route, '/');
} else {
- foreach (preg_split('/((\-?\/?)\{[^}]+\})/', $route) as $key => $t) {
+ foreach (preg_split('/((-?\/?){[^}]+})/', $route) as $key => $t) {
$regex = '';
@@ -155,13 +134,11 @@ abstract class Route implements IRoute
/* If custom regex is defined, use that */
if (isset($this->where[$name]) === true) {
$regex = $this->where[$name];
- } else if ($parameterRegex !== null) {
- $regex = $parameterRegex;
} else {
- $regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
+ $regex = $parameterRegex ?? $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
}
- $regex = sprintf('((\/|\-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
+ $regex = sprintf('((\/|-)(?P<%2$s>%3$s))%1$s', $parameters[2][$key], $name, $regex);
}
$urlRegex .= preg_quote($t, '/') . $regex;
@@ -273,7 +250,7 @@ abstract class Route implements IRoute
/**
* Set callback
*
- * @param string $callback
+ * @param string|array|\Closure $callback
* @return static
*/
public function setCallback($callback): IRoute
@@ -293,6 +270,10 @@ abstract class Route implements IRoute
public function getMethod(): ?string
{
+ if (\is_array($this->callback) === true && \count($this->callback) > 1) {
+ return $this->callback[1];
+ }
+
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
@@ -304,6 +285,10 @@ abstract class Route implements IRoute
public function getClass(): ?string
{
+ if (\is_array($this->callback) === true && \count($this->callback) > 0) {
+ return $this->callback[0];
+ }
+
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
@@ -315,14 +300,14 @@ abstract class Route implements IRoute
public function setMethod(string $method): IRoute
{
- $this->callback = sprintf('%s@%s', $this->getClass(), $method);
+ $this->callback = [$this->getClass(), $method];
return $this;
}
public function setClass(string $class): IRoute
{
- $this->callback = sprintf('%s@%s', $class, $this->getMethod());
+ $this->callback = [$class, $this->getMethod()];
return $this;
}
@@ -342,7 +327,7 @@ abstract class Route implements IRoute
* @param string $namespace
* @return static
*/
- public function setDefaultNamespace($namespace): IRoute
+ public function setDefaultNamespace(string $namespace): IRoute
{
$this->defaultNamespace = $namespace;
@@ -397,35 +382,35 @@ abstract class Route implements IRoute
/**
* Merge with information from another route.
*
- * @param array $values
+ * @param array $settings
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, bool $merge = false): IRoute
+ public function setSettings(array $settings, bool $merge = false): IRoute
{
- if ($this->namespace === null && isset($values['namespace']) === true) {
- $this->setNamespace($values['namespace']);
+ if ($this->namespace === null && isset($settings['namespace']) === true) {
+ $this->setNamespace($settings['namespace']);
}
- if (isset($values['method']) === true) {
- $this->setRequestMethods(array_merge($this->requestMethods, (array)$values['method']));
+ if (isset($settings['method']) === true) {
+ $this->setRequestMethods(array_merge($this->requestMethods, (array)$settings['method']));
}
- if (isset($values['where']) === true) {
- $this->setWhere(array_merge($this->where, (array)$values['where']));
+ if (isset($settings['where']) === true) {
+ $this->setWhere(array_merge($this->where, (array)$settings['where']));
}
- if (isset($values['parameters']) === true) {
- $this->setParameters(array_merge($this->parameters, (array)$values['parameters']));
+ if (isset($settings['parameters']) === true) {
+ $this->setParameters(array_merge($this->parameters, (array)$settings['parameters']));
}
// Push middleware if multiple
- if (isset($values['middleware']) === true) {
- $this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares));
+ if (isset($settings['middleware']) === true) {
+ $this->setMiddlewares(array_merge((array)$settings['middleware'], $this->middlewares));
}
- if (isset($values['defaultParameterRegex']) === true) {
- $this->setDefaultParameterRegex($values['defaultParameterRegex']);
+ if (isset($settings['defaultParameterRegex']) === true) {
+ $this->setDefaultParameterRegex($settings['defaultParameterRegex']);
}
return $this;
@@ -458,9 +443,9 @@ abstract class Route implements IRoute
* Add regular expression parameter match.
* Alias for LoadableRoute::where()
*
- * @see LoadableRoute::where()
* @param array $options
* @return static
+ * @see LoadableRoute::where()
*/
public function where(array $options)
{
@@ -508,11 +493,11 @@ abstract class Route implements IRoute
/**
* Add middleware class-name
*
- * @deprecated This method is deprecated and will be removed in the near future.
- * @param IMiddleware|string $middleware
+ * @param string $middleware
* @return static
+ * @deprecated This method is deprecated and will be removed in the near future.
*/
- public function setMiddleware($middleware)
+ public function setMiddleware(string $middleware): self
{
$this->middlewares[] = $middleware;
@@ -522,10 +507,10 @@ abstract class Route implements IRoute
/**
* Add middleware class-name
*
- * @param IMiddleware|string $middleware
+ * @param string $middleware
* @return static
*/
- public function addMiddleware($middleware): IRoute
+ public function addMiddleware(string $middleware): IRoute
{
$this->middlewares[] = $middleware;
@@ -560,7 +545,7 @@ abstract class Route implements IRoute
* @param string $regex
* @return static
*/
- public function setDefaultParameterRegex($regex)
+ public function setDefaultParameterRegex(string $regex): self
{
$this->defaultParameterRegex = $regex;
@@ -577,4 +562,25 @@ abstract class Route implements IRoute
return $this->defaultParameterRegex;
}
+ /**
+ * If enabled parameters containing null-value will not be passed along to the callback.
+ *
+ * @param bool $enabled
+ * @return static $this
+ */
+ public function setFilterEmptyParams(bool $enabled): IRoute
+ {
+ $this->filterEmptyParams = $enabled;
+ return $this;
+ }
+
+ /**
+ * Status if filtering of empty params is enabled or disabled
+ * @return bool
+ */
+ public function getFilterEmptyParams(): bool
+ {
+ return $this->filterEmptyParams;
+ }
+
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Route/RouteController.php b/src/Pecee/SimpleRouter/Route/RouteController.php
index 09091f1..2b00ec5 100644
--- a/src/Pecee/SimpleRouter/Route/RouteController.php
+++ b/src/Pecee/SimpleRouter/Route/RouteController.php
@@ -64,7 +64,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
if ($method !== null) {
/* Remove requestType from method-name, if it exists */
- foreach (static::$requestTypes as $requestType) {
+ foreach (Request::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, \strlen($requestType));
@@ -86,7 +86,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
return '/' . trim($url, '/') . '/';
}
- public function matchRoute($url, Request $request): bool
+ public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
@@ -110,7 +110,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$this->parameters = \array_slice($path, 1);
// Set callback
- $this->setCallback($this->controller . '@' . $this->method);
+ $this->setCallback([$this->controller, $this->method]);
return true;
}
@@ -167,17 +167,17 @@ class RouteController extends LoadableRoute implements IControllerRoute
/**
* Merge with information from another route.
*
- * @param array $values
+ * @param array $settings
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, bool $merge = false): IRoute
+ public function setSettings(array $settings, bool $merge = false): IRoute
{
- if (isset($values['names']) === true) {
- $this->names = $values['names'];
+ if (isset($settings['names']) === true) {
+ $this->names = $settings['names'];
}
- return parent::setSettings($values, $merge);
+ return parent::setSettings($settings, $merge);
}
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Route/RouteGroup.php b/src/Pecee/SimpleRouter/Route/RouteGroup.php
index 2f5e1d9..68e9e75 100644
--- a/src/Pecee/SimpleRouter/Route/RouteGroup.php
+++ b/src/Pecee/SimpleRouter/Route/RouteGroup.php
@@ -26,12 +26,15 @@ class RouteGroup extends Route implements IGroupRoute
foreach ($this->domains as $domain) {
+ // If domain has no parameters but matches
+ if ($domain === $request->getHost()) {
+ return true;
+ }
+
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
if ($parameters !== null && \count($parameters) !== 0) {
-
$this->parameters = $parameters;
-
return true;
}
}
@@ -46,14 +49,22 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @return bool
*/
- public function matchRoute($url, Request $request): bool
+ public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
+ // Parse parameter
+
+ $prefix = $this->prefix;
+
+ foreach ($this->getParameters() as $parameter => $value) {
+ $prefix = str_ireplace('{' . $parameter . '}', $value, $prefix);
+ }
+
/* Skip if prefix doesn't match */
- if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
+ if ($this->prefix !== null && stripos($url, $prefix) === false) {
return false;
}
@@ -123,7 +134,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix
* @return static
*/
- public function setPrefix($prefix): IGroupRoute
+ public function setPrefix(string $prefix): IGroupRoute
{
$this->prefix = '/' . trim($prefix, '/');
@@ -143,28 +154,28 @@ class RouteGroup extends Route implements IGroupRoute
/**
* Merge with information from another route.
*
- * @param array $values
+ * @param array $settings
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, bool $merge = false): IRoute
+ public function setSettings(array $settings, bool $merge = false): IRoute
{
- if (isset($values['prefix']) === true) {
- $this->setPrefix($values['prefix'] . $this->prefix);
+ if (isset($settings['prefix']) === true) {
+ $this->setPrefix($settings['prefix'] . $this->prefix);
}
- if ($merge === false && isset($values['exceptionHandler']) === true) {
- $this->setExceptionHandlers((array)$values['exceptionHandler']);
+ if ($merge === false && isset($settings['exceptionHandler']) === true) {
+ $this->setExceptionHandlers((array)$settings['exceptionHandler']);
}
- if ($merge === false && isset($values['domain']) === true) {
- $this->setDomains((array)$values['domain']);
+ if ($merge === false && isset($settings['domain']) === true) {
+ $this->setDomains((array)$settings['domain']);
}
- if (isset($values['as']) === true) {
+ if (isset($settings['as']) === true) {
- $name = $values['as'];
+ $name = $settings['as'];
if ($this->name !== null && $merge !== false) {
$name .= '.' . $this->name;
@@ -173,7 +184,7 @@ class RouteGroup extends Route implements IGroupRoute
$this->name = $name;
}
- return parent::setSettings($values, $merge);
+ return parent::setSettings($settings, $merge);
}
/**
diff --git a/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php b/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php
index 956c248..1e1a51b 100644
--- a/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php
+++ b/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php
@@ -22,7 +22,7 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
* @param Request $request
* @return bool
*/
- public function matchRoute($url, Request $request): bool
+ public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
@@ -38,7 +38,7 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
}
/* Set the parameters */
- $this->setParameters((array)$parameters);
+ $this->setParameters($parameters);
}
return $this->matchDomain($request);
diff --git a/src/Pecee/SimpleRouter/Route/RouteResource.php b/src/Pecee/SimpleRouter/Route/RouteResource.php
index 1795ec4..73ea662 100644
--- a/src/Pecee/SimpleRouter/Route/RouteResource.php
+++ b/src/Pecee/SimpleRouter/Route/RouteResource.php
@@ -76,14 +76,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return $this->url;
}
- protected function call($method)
+ protected function call($method): bool
{
- $this->setCallback($this->controller . '@' . $method);
+ $this->setCallback([$this->controller, $method]);
return true;
}
- public function matchRoute($url, Request $request): bool
+ public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
@@ -115,32 +115,32 @@ class RouteResource extends LoadableRoute implements IControllerRoute
$method = $request->getMethod();
// Delete
- if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
+ if ($method === Request::REQUEST_TYPE_DELETE && $id !== null) {
return $this->call($this->methodNames['destroy']);
}
// Update
- if ($id !== null && \in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], true) === true) {
+ if ($id !== null && \in_array($method, [Request::REQUEST_TYPE_PATCH, Request::REQUEST_TYPE_PUT], true) === true) {
return $this->call($this->methodNames['update']);
}
// Edit
- if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
+ if ($method === Request::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
return $this->call($this->methodNames['edit']);
}
// Create
- if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
+ if ($method === Request::REQUEST_TYPE_GET && $id === 'create') {
return $this->call($this->methodNames['create']);
}
// Save
- if ($method === static::REQUEST_TYPE_POST) {
+ if ($method === Request::REQUEST_TYPE_POST) {
return $this->call($this->methodNames['store']);
}
// Show
- if ($method === static::REQUEST_TYPE_GET && $id !== null) {
+ if ($method === Request::REQUEST_TYPE_GET && $id !== null) {
return $this->call($this->methodNames['show']);
}
@@ -190,7 +190,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param array $names
* @return static $this
*/
- public function setMethodNames(array $names)
+ public function setMethodNames(array $names): RouteResource
{
$this->methodNames = $names;
@@ -210,21 +210,21 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* Merge with information from another route.
*
- * @param array $values
+ * @param array $settings
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, bool $merge = false): IRoute
+ public function setSettings(array $settings, bool $merge = false): IRoute
{
- if (isset($values['names']) === true) {
- $this->names = $values['names'];
+ if (isset($settings['names']) === true) {
+ $this->names = $settings['names'];
}
- if (isset($values['methods']) === true) {
- $this->methodNames = $values['methods'];
+ if (isset($settings['methods']) === true) {
+ $this->methodNames = $settings['methods'];
}
- return parent::setSettings($values, $merge);
+ return parent::setSettings($settings, $merge);
}
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Route/RouteUrl.php b/src/Pecee/SimpleRouter/Route/RouteUrl.php
index cdfcb60..a4f62c1 100644
--- a/src/Pecee/SimpleRouter/Route/RouteUrl.php
+++ b/src/Pecee/SimpleRouter/Route/RouteUrl.php
@@ -12,7 +12,7 @@ class RouteUrl extends LoadableRoute
$this->setCallback($callback);
}
- public function matchRoute($url, Request $request): bool
+ public function matchRoute(string $url, Request $request): bool
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
diff --git a/src/Pecee/SimpleRouter/Router.php b/src/Pecee/SimpleRouter/Router.php
index 8d70ebc..91b7b67 100644
--- a/src/Pecee/SimpleRouter/Router.php
+++ b/src/Pecee/SimpleRouter/Router.php
@@ -110,6 +110,13 @@ class Router
*/
protected $classLoader;
+ /**
+ * When enabled the router will render all routes that matches.
+ * When disabled the router will stop execution when first route is found.
+ * @var bool
+ */
+ protected $renderMultipleRoutes = true;
+
/**
* Router constructor.
*/
@@ -262,13 +269,20 @@ class Router
/**
* Load routes
- * @throws NotFoundHttpException
* @return void
+ * @throws NotFoundHttpException
*/
public function loadRoutes(): void
{
$this->debug('Loading routes');
+ $this->fireEvents(EventHandler::EVENT_LOAD_ROUTES, [
+ 'routes' => $this->routes,
+ ]);
+
+ /* Loop through each route-request */
+ $this->processRoutes($this->routes);
+
$this->fireEvents(EventHandler::EVENT_BOOT, [
'bootmanagers' => $this->bootManagers,
]);
@@ -291,13 +305,6 @@ class Router
$this->debug('Finished rendering bootmanager "%s"', $className);
}
- $this->fireEvents(EventHandler::EVENT_LOAD_ROUTES, [
- 'routes' => $this->routes,
- ]);
-
- /* Loop through each route-request */
- $this->processRoutes($this->routes);
-
$this->debug('Finished loading routes');
}
@@ -305,7 +312,7 @@ class Router
* Start the routing
*
* @return string|null
- * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
+ * @throws NotFoundHttpException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException
* @throws \Exception
@@ -350,7 +357,7 @@ class Router
{
$this->debug('Routing request');
- $methodNotAllowed = false;
+ $methodNotAllowed = null;
try {
$url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
@@ -370,7 +377,12 @@ class Router
/* Check if request method matches */
if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$this->debug('Method "%s" not allowed', $this->request->getMethod());
- $methodNotAllowed = true;
+
+ // Only set method not allowed is not already set
+ if ($methodNotAllowed === null) {
+ $methodNotAllowed = true;
+ }
+
continue;
}
@@ -394,14 +406,21 @@ class Router
'route' => $route,
]);
- $output = $route->renderRoute($this->request, $this);
- if ($output !== null) {
- return $output;
- }
+ $routeOutput = $route->renderRoute($this->request, $this);
- $output = $this->handleRouteRewrite($key, $url);
- if ($output !== null) {
- return $output;
+ if ($this->renderMultipleRoutes === true) {
+ if ($routeOutput !== null) {
+ return $routeOutput;
+ }
+
+ $output = $this->handleRouteRewrite($key, $url);
+ if ($output !== null) {
+ return $output;
+ }
+ } else {
+ $output = $this->handleRouteRewrite($key, $url);
+
+ return $output ?? $routeOutput;
}
}
}
@@ -442,7 +461,7 @@ class Router
* @throws HttpException
* @throws \Exception
*/
- protected function handleRouteRewrite($key, string $url): ?string
+ protected function handleRouteRewrite(string $key, string $url): ?string
{
/* If the request has changed */
if ($this->request->hasPendingRewrite() === false) {
@@ -475,9 +494,9 @@ class Router
/**
* @param \Exception $e
- * @throws HttpException
- * @throws \Exception
* @return string|null
+ * @throws \Exception
+ * @throws HttpException
*/
protected function handleException(\Exception $e): ?string
{
@@ -585,7 +604,7 @@ class Router
/* Check if callback matches (if it's not a function) */
$callback = $route->getCallback();
- if (\is_string($name) === true && \is_string($callback) === true && strpos($name, '@') !== false && strpos($callback, '@') !== false && \is_callable($callback) === false) {
+ if (\is_string($name) === true && \is_string($callback) === true && \is_callable($callback) === false && strpos($name, '@') !== false && strpos($callback, '@') !== false) {
/* Check if the entire callback is matching */
if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) {
@@ -625,7 +644,6 @@ class Router
* @param array|null $getParams
* @return Url
* @throws InvalidArgumentException
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url
{
@@ -665,14 +683,16 @@ class Router
->setParams($getParams);
}
- /* We try to find a match on the given name */
- $route = $this->findRoute($name);
+ if($name !== null) {
+ /* We try to find a match on the given name */
+ $route = $this->findRoute($name);
- if ($route !== null) {
- return $this->request
- ->getUrlCopy()
- ->setPath($route->findUrl($route->getMethod(), $parameters, $name))
- ->setParams($getParams);
+ if ($route !== null) {
+ return $this->request
+ ->getUrlCopy()
+ ->setPath($route->findUrl($route->getMethod(), $parameters, $name))
+ ->setParams($getParams);
+ }
}
/* Using @ is most definitely a controller@method or alias@method */
@@ -854,7 +874,7 @@ class Router
* @param string $name
* @param array $arguments
*/
- protected function fireEvents($name, array $arguments = []): void
+ protected function fireEvents(string $name, array $arguments = []): void
{
if (\count($this->eventHandlers) === 0) {
return;
@@ -908,4 +928,19 @@ class Router
return $this->debugList;
}
+ /**
+ * Changes the rendering behavior of the router.
+ * When enabled the router will render all routes that matches.
+ * When disabled the router will stop rendering at the first route that matches.
+ *
+ * @param bool $bool
+ * @return $this
+ */
+ public function setRenderMultipleRoutes(bool $bool): self
+ {
+ $this->renderMultipleRoutes = $bool;
+
+ return $this;
+ }
+
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/SimpleRouter.php b/src/Pecee/SimpleRouter/SimpleRouter.php
index cd1b61c..408a8d2 100644
--- a/src/Pecee/SimpleRouter/SimpleRouter.php
+++ b/src/Pecee/SimpleRouter/SimpleRouter.php
@@ -10,9 +10,7 @@
namespace Pecee\SimpleRouter;
-use DI\Container;
use Pecee\Exceptions\InvalidArgumentException;
-use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response;
@@ -60,6 +58,11 @@ class SimpleRouter
*/
public static function start(): void
{
+ // Set default namespaces
+ foreach (static::router()->getRoutes() as $route) {
+ static::addDefaultNamespace($route);
+ }
+
echo static::router()->start();
}
@@ -75,8 +78,7 @@ class SimpleRouter
try {
ob_start();
static::router()->setDebugEnabled(true)->start();
- $routerOutput = ob_get_contents();
- ob_end_clean();
+ $routerOutput = ob_get_clean();
} catch (\Exception $e) {
}
@@ -167,7 +169,7 @@ class SimpleRouter
* @param int $httpCode
* @return IRoute
*/
- public static function redirect($where, $to, $httpCode = 301): IRoute
+ public static function redirect(string $where, string $to, int $httpCode = 301): IRoute
{
return static::get($where, function () use ($to, $httpCode) {
static::response()->redirect($to, $httpCode);
@@ -178,79 +180,79 @@ class SimpleRouter
* Route the given url to your callback on GET request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
*
* @return RouteUrl
*/
public static function get(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['get'], $url, $callback, $settings);
+ return static::match([Request::REQUEST_TYPE_GET], $url, $callback, $settings);
}
/**
* Route the given url to your callback on POST request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function post(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['post'], $url, $callback, $settings);
+ return static::match([Request::REQUEST_TYPE_POST], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PUT request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function put(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['put'], $url, $callback, $settings);
+ return static::match([Request::REQUEST_TYPE_PUT], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PATCH request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function patch(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['patch'], $url, $callback, $settings);
+ return static::match([Request::REQUEST_TYPE_PATCH], $url, $callback, $settings);
}
/**
* Route the given url to your callback on OPTIONS request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function options(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['options'], $url, $callback, $settings);
+ return static::match([Request::REQUEST_TYPE_OPTIONS], $url, $callback, $settings);
}
/**
* Route the given url to your callback on DELETE request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function delete(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['delete'], $url, $callback, $settings);
+ return static::match([Request::REQUEST_TYPE_DELETE], $url, $callback, $settings);
}
/**
@@ -307,14 +309,14 @@ class SimpleRouter
* Alias for the form method
*
* @param string $url
- * @param callable $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
- * @see SimpleRouter::form
* @return RouteUrl
+ * @see SimpleRouter::form
*/
public static function basic(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['get', 'post'], $url, $callback, $settings);
+ return static::form($url, $callback, $settings);
}
/**
@@ -322,14 +324,17 @@ class SimpleRouter
* Route the given url to your callback on POST and GET request method.
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
- * @see SimpleRouter::form
* @return RouteUrl
+ * @see SimpleRouter::form
*/
public static function form(string $url, $callback, array $settings = null): IRoute
{
- return static::match(['get', 'post'], $url, $callback, $settings);
+ return static::match([
+ Request::REQUEST_TYPE_GET,
+ Request::REQUEST_TYPE_POST,
+ ], $url, $callback, $settings);
}
/**
@@ -337,7 +342,7 @@ class SimpleRouter
*
* @param array $requestMethods
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
*/
@@ -345,7 +350,6 @@ class SimpleRouter
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
- $route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -358,14 +362,13 @@ class SimpleRouter
* This type will route the given url to your callback and allow any type of request method
*
* @param string $url
- * @param string|\Closure $callback
+ * @param string|array|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
*/
public static function all(string $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
- $route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -382,10 +385,9 @@ class SimpleRouter
* @param array|null $settings
* @return RouteController|IRoute
*/
- public static function controller(string $url, $controller, array $settings = null)
+ public static function controller(string $url, string $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
- $route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -402,10 +404,9 @@ class SimpleRouter
* @param array|null $settings
* @return RouteResource|IRoute
*/
- public static function resource(string $url, $controller, array $settings = null)
+ public static function resource(string $url, string $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
- $route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -458,21 +459,14 @@ class SimpleRouter
try {
return static::router()->getUrl($name, $parameters, $getParams);
} catch (\Exception $e) {
- try {
- return new Url('/');
- } catch (MalformedUrlException $e) {
-
- }
+ return new Url('/');
}
-
- // This will never happen...
- return null;
}
/**
* Get the request
*
- * @return \Pecee\Http\Request
+ * @return Request
*/
public static function request(): Request
{
@@ -517,39 +511,43 @@ class SimpleRouter
{
if (static::$defaultNamespace !== null) {
- $callback = $route->getCallback();
+ $ns = static::$defaultNamespace;
+ $namespace = $route->getNamespace();
- /* Only add default namespace on relative callbacks */
- if ($callback === null || (\is_string($callback) === true && $callback[0] !== '\\')) {
-
- $namespace = static::$defaultNamespace;
-
- $currentNamespace = $route->getNamespace();
-
- if ($currentNamespace !== null) {
- $namespace .= '\\' . $currentNamespace;
+ if ($namespace !== null) {
+ // Don't overwrite namespaces that starts with \
+ if ($namespace[0] !== '\\') {
+ $ns .= '\\' . $namespace;
+ } else {
+ $ns = $namespace;
}
-
- $route->setDefaultNamespace($namespace);
-
}
+
+ $route->setNamespace($ns);
}
return $route;
}
/**
- * Enable or disable dependency injection
+ * Changes the rendering behavior of the router.
+ * When enabled the router will render all routes that matches.
+ * When disabled the router will stop rendering at the first route that matches.
*
- * @param Container $container
- * @return IClassLoader
+ * @param bool $bool
*/
- public static function enableDependencyInjection(Container $container): IClassLoader
+ public static function enableMultiRouteRendering(bool $bool): void
{
- return static::router()
- ->getClassLoader()
- ->useDependencyInjection(true)
- ->setContainer($container);
+ static::router()->setRenderMultipleRoutes($bool);
+ }
+
+ /**
+ * Set custom class-loader class used.
+ * @param IClassLoader $classLoader
+ */
+ public static function setCustomClassLoader(IClassLoader $classLoader): void
+ {
+ static::router()->setClassLoader($classLoader);
}
/**
diff --git a/tests/Pecee/SimpleRouter/BootManagerTest.php b/tests/Pecee/SimpleRouter/BootManagerTest.php
new file mode 100644
index 0000000..925ea97
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/BootManagerTest.php
@@ -0,0 +1,49 @@
+ '/about',
+ '/contact' => '/',
+ ]));
+
+ TestRouter::debug('/contact');
+
+ $this->assertTrue($result);
+ }
+
+ public function testFindUrlFromBootManager()
+ {
+ TestRouter::get('/', 'DummyController@method1');
+ TestRouter::get('/about', 'DummyController@method2')->name('about');
+ TestRouter::get('/contact', 'DummyController@method3')->name('contact');
+
+ $result = false;
+
+ // Add boot-manager
+ TestRouter::addBootManager(new FindUrlBootManager($result));
+
+ TestRouter::debug('/');
+
+ $this->assertTrue($result);
+ }
+
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/ClassLoaderTest.php b/tests/Pecee/SimpleRouter/ClassLoaderTest.php
new file mode 100644
index 0000000..79f6095
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/ClassLoaderTest.php
@@ -0,0 +1,30 @@
+assertEquals('method3', $classLoaderClass);
+ $this->assertTrue($result);
+
+ TestRouter::router()->reset();
+ }
+
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/DependencyInjectionTest.php b/tests/Pecee/SimpleRouter/DependencyInjectionTest.php
deleted file mode 100644
index 8863f19..0000000
--- a/tests/Pecee/SimpleRouter/DependencyInjectionTest.php
+++ /dev/null
@@ -1,53 +0,0 @@
-useAutowiring(true)
- ->ignorePhpDocErrors(true)
- ->build();
-
- TestRouter::enableDependencyInjection($container);
-
- $className = null;
-
- TestRouter::get('/', function (DummyMiddleware $url) use (&$className) {
- $className = \get_class($url);
- });
-
- TestRouter::debug('/');
-
- $this->assertEquals(DummyMiddleware::class, $className);
- }
-
- public function testDependencyInjectionProduction()
- {
- $cacheDir = dirname(__DIR__, 2) . '/tmp';
-
- $builder = new \DI\ContainerBuilder();
- $builder
- ->enableCompilation($cacheDir)
- ->writeProxiesToFile(true, $cacheDir . '/proxies')
- ->ignorePhpDocErrors(true)
- ->useAutowiring(true);
-
- $container = $builder->build();
-
- TestRouter::enableDependencyInjection($container);
-
- $className = null;
-
- TestRouter::get('/', function (DummyMiddleware $url) use (&$className) {
- $className = \get_class($url);
- });
-
- TestRouter::debug('/');
-
- $this->assertEquals(DummyMiddleware::class, $className);
- }
-}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/Dummy/ClassLoader/CustomClassLoader.php b/tests/Pecee/SimpleRouter/Dummy/ClassLoader/CustomClassLoader.php
new file mode 100644
index 0000000..17bff54
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/Dummy/ClassLoader/CustomClassLoader.php
@@ -0,0 +1,14 @@
+ true]);
+ }
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/Dummy/DummyController.php b/tests/Pecee/SimpleRouter/Dummy/DummyController.php
index 8e38c2d..3b25e5d 100644
--- a/tests/Pecee/SimpleRouter/Dummy/DummyController.php
+++ b/tests/Pecee/SimpleRouter/Dummy/DummyController.php
@@ -2,6 +2,12 @@
class DummyController
{
+ public function index()
+ {
+
+ }
+
+
public function method1()
{
@@ -10,6 +16,11 @@ class DummyController
public function method2()
{
+ }
+
+ public function method3()
+ {
+ return 'method3';
}
public function param($params = null)
diff --git a/tests/Pecee/SimpleRouter/Dummy/Managers/FindUrlBootManager.php b/tests/Pecee/SimpleRouter/Dummy/Managers/FindUrlBootManager.php
new file mode 100644
index 0000000..f8bdcf3
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/Dummy/Managers/FindUrlBootManager.php
@@ -0,0 +1,26 @@
+result = &$result;
+ }
+
+ /**
+ * Called when router loads it's routes
+ *
+ * @param \Pecee\SimpleRouter\Router $router
+ * @param \Pecee\Http\Request $request
+ */
+ public function boot(\Pecee\SimpleRouter\Router $router, \Pecee\Http\Request $request): void
+ {
+ $contact = $router->findRoute('contact');
+
+ if($contact !== null) {
+ $this->result = true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/Dummy/Managers/TestBootManager.php b/tests/Pecee/SimpleRouter/Dummy/Managers/TestBootManager.php
index 8516aae..1617b46 100644
--- a/tests/Pecee/SimpleRouter/Dummy/Managers/TestBootManager.php
+++ b/tests/Pecee/SimpleRouter/Dummy/Managers/TestBootManager.php
@@ -3,13 +3,11 @@
class TestBootManager implements \Pecee\SimpleRouter\IRouterBootManager
{
- protected $routes;
- protected $aliasUrl;
+ protected $rewrite;
- public function __construct(array $routes, string $aliasUrl)
+ public function __construct(array $rewrite)
{
- $this->routes = $routes;
- $this->aliasUrl = $aliasUrl;
+ $this->rewrite = $rewrite;
}
/**
@@ -20,11 +18,11 @@ class TestBootManager implements \Pecee\SimpleRouter\IRouterBootManager
*/
public function boot(\Pecee\SimpleRouter\Router $router, \Pecee\Http\Request $request): void
{
- foreach ($this->routes as $url) {
+ foreach ($this->rewrite as $url => $rewrite) {
// If the current url matches the rewrite url, we use our custom route
if ($request->getUrl()->contains($url) === true) {
- $request->setRewriteUrl($this->aliasUrl);
+ $request->setRewriteUrl($rewrite);
}
}
diff --git a/tests/Pecee/SimpleRouter/Dummy/ResourceController.php b/tests/Pecee/SimpleRouter/Dummy/ResourceController.php
index 0a70e6f..bd36ab3 100644
--- a/tests/Pecee/SimpleRouter/Dummy/ResourceController.php
+++ b/tests/Pecee/SimpleRouter/Dummy/ResourceController.php
@@ -4,43 +4,36 @@ class ResourceController implements \Pecee\Controllers\IResourceController
public function index() : ?string
{
- echo 'index';
- return null;
+ return 'index';
}
public function show($id) : ?string
{
- echo 'show ' . $id;
- return null;
+ return 'show ' . $id;
}
public function store() : ?string
{
- echo 'store';
- return null;
+ return 'store';
}
public function create() : ?string
{
- echo 'create';
- return null;
+ return 'create';
}
public function edit($id) : ?string
{
- echo 'edit ' . $id;
- return null;
+ return 'edit ' . $id;
}
public function update($id) : ?string
{
- echo 'update ' . $id;
- return null;
+ return 'update ' . $id;
}
public function destroy($id) : ?string
{
- echo 'destroy ' . $id;
- return null;
+ return 'destroy ' . $id;
}
}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/EventHandlerTest.php b/tests/Pecee/SimpleRouter/EventHandlerTest.php
index 8fa873d..faaa5d9 100644
--- a/tests/Pecee/SimpleRouter/EventHandlerTest.php
+++ b/tests/Pecee/SimpleRouter/EventHandlerTest.php
@@ -50,8 +50,8 @@ class EventHandlerTest extends \PHPUnit\Framework\TestCase
// Add boot-manager
TestRouter::addBootManager(new TestBootManager([
- '/test',
- ], '/'));
+ '/test' => '/',
+ ]));
// Start router
TestRouter::debug('/non-existing');
@@ -61,7 +61,6 @@ class EventHandlerTest extends \PHPUnit\Framework\TestCase
public function testAllEvent()
{
-
$status = false;
$eventHandler = new EventHandler();
diff --git a/tests/Pecee/SimpleRouter/InputHandlerTest.php b/tests/Pecee/SimpleRouter/InputHandlerTest.php
index 205d57e..11dcf28 100644
--- a/tests/Pecee/SimpleRouter/InputHandlerTest.php
+++ b/tests/Pecee/SimpleRouter/InputHandlerTest.php
@@ -1,28 +1,44 @@
'Pepsi',
+ 1 => 'Coca Cola',
+ 2 => 'Harboe',
+ 3 => 'Mountain Dew',
+ ];
+
+ protected $day = 'monday';
public function testPost()
{
global $_POST;
- $names = [
- 'Lester',
- 'Michael',
- 'Franklin',
- 'Trevor',
- ];
-
- $day = 'monday';
-
$_POST = [
- 'names' => $names,
- 'day' => $day,
+ 'names' => $this->names,
+ 'day' => $this->day,
+ 'sodas' => $this->sodas,
];
$router = TestRouter::router();
@@ -31,29 +47,34 @@ class InputHandlerTest extends \PHPUnit\Framework\TestCase
$handler = TestRouter::request()->getInputHandler();
- $this->assertEquals($names, $handler->value('names'));
- $this->assertEquals($names, $handler->all(['names'])['names']);
- $this->assertEquals($day, $handler->value('day'));
+ $this->assertEquals($this->names, $handler->value('names'));
+ $this->assertEquals($this->names, $handler->all(['names'])['names']);
+ $this->assertEquals($this->day, $handler->value('day'));
$this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $handler->find('day'));
$this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $handler->post('day'));
+ $this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $handler->find('day', 'post'));
// Check non-existing and wrong request-type
- $this->assertEmpty($handler->all(['non-existing']));
+ $this->assertCount(1, $handler->all(['non-existing']));
+ $this->assertEmpty($handler->all(['non-existing'])['non-existing']);
$this->assertNull($handler->value('non-existing'));
$this->assertNull($handler->find('non-existing'));
$this->assertNull($handler->value('names', null, 'get'));
$this->assertNull($handler->find('names', 'get'));
+ $this->assertEquals($this->sodas, $handler->value('sodas'));
$objects = $handler->find('names');
+ $this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $objects);
$this->assertCount(4, $objects);
/* @var $object \Pecee\Http\Input\InputItem */
foreach($objects as $i => $object) {
$this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $object);
- $this->assertEquals($names[$i], $object->getValue());
+ $this->assertEquals($this->names[$i], $object->getValue());
}
+ // Reset
$_POST = [];
}
@@ -61,18 +82,9 @@ class InputHandlerTest extends \PHPUnit\Framework\TestCase
{
global $_GET;
- $names = [
- 'Lester',
- 'Michael',
- 'Franklin',
- 'Trevor',
- ];
-
- $day = 'monday';
-
$_GET = [
- 'names' => $names,
- 'day' => $day,
+ 'names' => $this->names,
+ 'day' => $this->day,
];
$router = TestRouter::router();
@@ -81,14 +93,15 @@ class InputHandlerTest extends \PHPUnit\Framework\TestCase
$handler = TestRouter::request()->getInputHandler();
- $this->assertEquals($names, $handler->value('names'));
- $this->assertEquals($names, $handler->all(['names'])['names']);
- $this->assertEquals($day, $handler->value('day'));
+ $this->assertEquals($this->names, $handler->value('names'));
+ $this->assertEquals($this->names, $handler->all(['names'])['names']);
+ $this->assertEquals($this->day, $handler->value('day'));
$this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $handler->find('day'));
$this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $handler->get('day'));
// Check non-existing and wrong request-type
- $this->assertEmpty($handler->all(['non-existing']));
+ $this->assertCount(1, $handler->all(['non-existing']));
+ $this->assertEmpty($handler->all(['non-existing'])['non-existing']);
$this->assertNull($handler->value('non-existing'));
$this->assertNull($handler->find('non-existing'));
$this->assertNull($handler->value('names', null, 'post'));
@@ -96,30 +109,166 @@ class InputHandlerTest extends \PHPUnit\Framework\TestCase
$objects = $handler->find('names');
+ $this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $objects);
$this->assertCount(4, $objects);
/* @var $object \Pecee\Http\Input\InputItem */
foreach($objects as $i => $object) {
$this->assertInstanceOf(\Pecee\Http\Input\InputItem::class, $object);
- $this->assertEquals($names[$i], $object->getValue());
+ $this->assertEquals($this->names[$i], $object->getValue());
}
+ // Reset
$_GET = [];
}
+
+
public function testFile()
{
- $this->assertEquals(true, true);
+ global $_FILES;
+
+ $testFile = $this->generateFile();
+
+ $_FILES = [
+ 'test_input' => $testFile,
+ ];
+
+ $router = TestRouter::router();
+ $router->reset();
+ $router->getRequest()->setMethod('post');
+ $inputHandler = TestRouter::request()->getInputHandler();
+
+ $testFileContent = md5(uniqid('test', false));
+
+ $file = $inputHandler->file('test_input');
+
+ $this->assertInstanceOf(InputFile::class, $file);
+ $this->assertEquals($testFile['name'], $file->getFilename());
+ $this->assertEquals($testFile['type'], $file->getType());
+ $this->assertEquals($testFile['tmp_name'], $file->getTmpName());
+ $this->assertEquals($testFile['error'], $file->getError());
+ $this->assertEquals($testFile['size'], $file->getSize());
+ $this->assertEquals(pathinfo($testFile['name'], PATHINFO_EXTENSION), $file->getExtension());
+
+ file_put_contents($testFile['tmp_name'], $testFileContent);
+ $this->assertEquals($testFileContent, $file->getContents());
+
+ // Cleanup
+ unlink($testFile['tmp_name']);
}
- public function testFiles()
+ public function testFilesArray()
{
- $this->assertEquals(true, true);
+ global $_FILES;
+
+ $testFiles = [
+ $file = $this->generateFile(),
+ $file = $this->generateFile(),
+ $file = $this->generateFile(),
+ $file = $this->generateFile(),
+ $file = $this->generateFile(),
+ ];
+
+ $_FILES = [
+ 'my_files' => $testFiles,
+ ];
+
+ $router = TestRouter::router();
+ $router->reset();
+ $router->getRequest()->setMethod('post');
+ $inputHandler = TestRouter::request()->getInputHandler();
+
+ $files = $inputHandler->file('my_files');
+ $this->assertCount(5, $files);
+
+ /* @var $file InputFile */
+ foreach ($files as $key => $file) {
+
+ $testFileContent = md5(uniqid('test', false));
+
+ $this->assertInstanceOf(InputFile::class, $file);
+ $this->assertEquals($testFiles[$key]['name'], $file->getFilename());
+ $this->assertEquals($testFiles[$key]['type'], $file->getType());
+ $this->assertEquals($testFiles[$key]['tmp_name'], $file->getTmpName());
+ $this->assertEquals($testFiles[$key]['error'], $file->getError());
+ $this->assertEquals($testFiles[$key]['size'], $file->getSize());
+ $this->assertEquals(pathinfo($testFiles[$key]['name'], PATHINFO_EXTENSION), $file->getExtension());
+
+ file_put_contents($testFiles[$key]['tmp_name'], $testFileContent);
+
+ $this->assertEquals($testFileContent, $file->getContents());
+
+ // Cleanup
+ unlink($testFiles[$key]['tmp_name']);
+ }
+
}
public function testAll()
{
- $this->assertEquals(true, true);
+ global $_POST;
+ global $_GET;
+
+ $_POST = [
+ 'names' => $this->names,
+ 'is_sad' => true,
+ ];
+
+ $_GET = [
+ 'brands' => $this->brands,
+ 'is_happy' => true,
+ ];
+
+ $router = TestRouter::router();
+ $router->reset();
+ $router->getRequest()->setMethod('post');
+
+ $handler = TestRouter::request()->getInputHandler();
+
+ // GET
+ $brandsFound = $handler->all(['brands', 'nothing']);
+
+ $this->assertArrayHasKey('brands', $brandsFound);
+ $this->assertArrayHasKey('nothing', $brandsFound);
+ $this->assertEquals($this->brands, $brandsFound['brands']);
+ $this->assertNull($brandsFound['nothing']);
+
+ // POST
+ $namesFound = $handler->all(['names', 'nothing']);
+
+ $this->assertArrayHasKey('names', $namesFound);
+ $this->assertArrayHasKey('nothing', $namesFound);
+ $this->assertEquals($this->names, $namesFound['names']);
+ $this->assertNull($namesFound['nothing']);
+
+ // DEFAULT VALUE
+ $nonExisting = $handler->all([
+ 'non-existing'
+ ]);
+
+ $this->assertArrayHasKey('non-existing', $nonExisting);
+ $this->assertNull($nonExisting['non-existing']);
+
+ // Reset
+ $_GET = [];
+ $_POST = [];
+ }
+
+ protected function generateFile()
+ {
+ return [
+ 'name' => uniqid('', false) . '.txt',
+ 'type' => 'text/plain',
+ 'tmp_name' => sys_get_temp_dir() . '/phpYfWUiw',
+ 'error' => 0,
+ 'size' => rand(3, 40),
+ ];
+ }
+
+ protected function generateFileContent()
+ {
+ return md5(uniqid('', false));
}
}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/RequestTest.php b/tests/Pecee/SimpleRouter/RequestTest.php
new file mode 100644
index 0000000..b17256a
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/RequestTest.php
@@ -0,0 +1,84 @@
+reset();
+
+ $request = $router->getRequest();
+
+ $callback($request);
+
+ // Reset everything
+ $_SERVER[$name] = null;
+ $router->reset();
+ }
+
+ public function testContentTypeParse()
+ {
+ global $_SERVER;
+
+ // Test normal content-type
+
+ $contentType = 'application/x-www-form-urlencoded';
+
+ $this->processHeader('content_type', $contentType, function(\Pecee\Http\Request $request) use($contentType) {
+ $this->assertEquals($contentType, $request->getContentType());
+ });
+
+ // Test special content-type with encoding
+
+ $contentTypeWithEncoding = 'application/x-www-form-urlencoded; charset=UTF-8';
+
+ $this->processHeader('content_type', $contentTypeWithEncoding, function(\Pecee\Http\Request $request) use($contentType) {
+ $this->assertEquals($contentType, $request->getContentType());
+ });
+ }
+
+ public function testGetIp()
+ {
+ $ip = '1.1.1.1';
+ $this->processHeader('remote_addr', $ip, function(\Pecee\Http\Request $request) use($ip) {
+ $this->assertEquals($ip, $request->getIp());
+ });
+
+ $ip = '2.2.2.2';
+ $this->processHeader('http-cf-connecting-ip', $ip, function(\Pecee\Http\Request $request) use($ip) {
+ $this->assertEquals($ip, $request->getIp());
+ });
+
+ $ip = '3.3.3.3';
+ $this->processHeader('http-client-ip', $ip, function(\Pecee\Http\Request $request) use($ip) {
+ $this->assertEquals($ip, $request->getIp());
+ });
+
+ $ip = '4.4.4.4';
+ $this->processHeader('http-x-forwarded-for', $ip, function(\Pecee\Http\Request $request) use($ip) {
+ $this->assertEquals($ip, $request->getIp());
+ });
+
+ // Test safe
+
+ $ip = '5.5.5.5';
+ $this->processHeader('http-x-forwarded-for', $ip, function(\Pecee\Http\Request $request) {
+ $this->assertEquals(null, $request->getIp(true));
+ });
+
+ }
+
+ // TODO: implement more test-cases
+
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/RouterPartialGroupTest.php b/tests/Pecee/SimpleRouter/RouterPartialGroupTest.php
index 21c9fe2..40e288a 100644
--- a/tests/Pecee/SimpleRouter/RouterPartialGroupTest.php
+++ b/tests/Pecee/SimpleRouter/RouterPartialGroupTest.php
@@ -25,4 +25,49 @@ class RouterPartialGroupTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('param2', $result2);
}
+ /**
+ * Fixed issue with partial routes not loading child groups.
+ * Reported in issue: #456
+ */
+ public function testPartialGroupWithGroup() {
+
+ $lang = null;
+
+ $route1 = '/lang/da/test/';
+ $route2 = '/lang/da/auth';
+ $route3 = '/lang/da/auth/test';
+
+ TestRouter::partialGroup(
+ '/lang/{test}/',
+ function ($lang = 'en') use($route1, $route2, $route3) {
+
+ TestRouter::get('/test/', function () use($route1) {
+ return $route1;
+ });
+
+ TestRouter::group(['prefix' => '/auth/'], function () use($route2, $route3) {
+
+ TestRouter::get('/', function() use($route2) {
+ return $route2;
+ });
+
+ TestRouter::get('/test', function () use($route3){
+ return $route3;
+ });
+
+ });
+
+ }
+ );
+
+ $test1 = TestRouter::debugOutput('/lang/da/test', 'get', false);
+ $test2 = TestRouter::debugOutput('/lang/da/auth', 'get', false);
+ $test3 = TestRouter::debugOutput('/lang/da/auth/test', 'get', false);
+
+ $this->assertEquals($test1, $route1);
+ $this->assertEquals($test2, $route2);
+ $this->assertEquals($test3, $route3);
+
+ }
+
}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/RouterRewriteTest.php b/tests/Pecee/SimpleRouter/RouterRewriteTest.php
index c0692c1..5764638 100644
--- a/tests/Pecee/SimpleRouter/RouterRewriteTest.php
+++ b/tests/Pecee/SimpleRouter/RouterRewriteTest.php
@@ -6,7 +6,7 @@ require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Dummy/Middleware/RewriteMiddleware.php';
-class RouteRewriteTest extends \PHPUnit\Framework\TestCase
+class RouterRewriteTest extends \PHPUnit\Framework\TestCase
{
/**
diff --git a/tests/Pecee/SimpleRouter/RouterRouteTest.php b/tests/Pecee/SimpleRouter/RouterRouteTest.php
index 0571799..3a3d2c1 100644
--- a/tests/Pecee/SimpleRouter/RouterRouteTest.php
+++ b/tests/Pecee/SimpleRouter/RouterRouteTest.php
@@ -101,12 +101,48 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
public function testPathParamRegex()
{
- TestRouter::get('/{lang}/productscategories/{name}', 'DummyController@param', ['where' => ['lang' => '[a-z]+', 'name' => '[A-Za-z0-9\-]+']]);
+ TestRouter::get('/{lang}/productscategories/{name}', 'DummyController@param', ['where' => ['lang' => '[a-z]+', 'name' => '[A-Za-z0-9-]+']]);
$response = TestRouter::debugOutput('/it/productscategories/system', 'get');
$this->assertEquals('it, system', $response);
}
+ public function testFixedDomain()
+ {
+ $result = false;
+ TestRouter::request()->setHost('admin.world.com');
+
+ TestRouter::group(['domain' => 'admin.world.com'], function () use (&$result) {
+ TestRouter::get('/test', function ($subdomain = null) use (&$result) {
+ $result = true;
+ });
+ });
+
+ TestRouter::debug('/test', 'get');
+
+ $this->assertTrue($result);
+ }
+
+ public function testFixedNotAllowedDomain()
+ {
+ $result = false;
+ TestRouter::request()->setHost('other.world.com');
+
+ TestRouter::group(['domain' => 'admin.world.com'], function () use (&$result) {
+ TestRouter::get('/', function ($subdomain = null) use (&$result) {
+ $result = true;
+ });
+ });
+
+ try {
+ TestRouter::debug('/', 'get');
+ } catch(\Exception $e) {
+
+ }
+
+ $this->assertFalse($result);
+ }
+
public function testDomainAllowedRoute()
{
$result = false;
@@ -144,12 +180,27 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
public function testRegEx()
{
- TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
+ TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z-]+']);
TestRouter::debug('/my/custom-path', 'get');
$this->assertTrue(true);
}
+ public function testParametersWithDashes()
+ {
+
+ $defaultVariable = null;
+
+ TestRouter::get('/my/{path}', function ($path = 'working') use (&$defaultVariable) {
+ $defaultVariable = $path;
+ });
+
+ TestRouter::debug('/my/hello-motto-man');
+
+ $this->assertEquals('hello-motto-man', $defaultVariable);
+
+ }
+
public function testParameterDefaultValue()
{
@@ -167,7 +218,7 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
public function testDefaultParameterRegex()
{
- TestRouter::get('/my/{path}', 'DummyController@param', ['defaultParameterRegex' => '[\w\-]+']);
+ TestRouter::get('/my/{path}', 'DummyController@param', ['defaultParameterRegex' => '[\w-]+']);
$output = TestRouter::debugOutput('/my/custom-regex', 'get');
$this->assertEquals('custom-regex', $output);
@@ -175,7 +226,7 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
public function testDefaultParameterRegexGroup()
{
- TestRouter::group(['defaultParameterRegex' => '[\w\-]+'], function () {
+ TestRouter::group(['defaultParameterRegex' => '[\w-]+'], function () {
TestRouter::get('/my/{path}', 'DummyController@param');
});
@@ -184,4 +235,26 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('custom-regex', $output);
}
+ public function testClassHint()
+ {
+ TestRouter::get('/my/test/url', ['DummyController', 'method1']);
+ TestRouter::all('/my/test/url', ['DummyController', 'method1']);
+ TestRouter::match(['put', 'get', 'post'], '/my/test/url', ['DummyController', 'method1']);
+
+ TestRouter::debug('/my/test/url', 'get');
+
+ $this->assertTrue(true);
+ }
+
+ public function testSameRoutes()
+ {
+ TestRouter::get('/recipe', 'DummyController@method1')->name('add');
+ TestRouter::post('/recipe', 'DummyController@method2')->name('edit');
+
+ TestRouter::debugNoReset('/recipe', 'post');
+ TestRouter::debug('/recipe', 'get');
+
+ $this->assertTrue(true);
+ }
+
}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/RouterUrlTest.php b/tests/Pecee/SimpleRouter/RouterUrlTest.php
index 78f9e1a..f9b0d4b 100644
--- a/tests/Pecee/SimpleRouter/RouterUrlTest.php
+++ b/tests/Pecee/SimpleRouter/RouterUrlTest.php
@@ -11,7 +11,7 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
{
TestRouter::get('/', 'DummyController@method1');
TestRouter::get('/page/{id?}', 'DummyController@method1');
- TestRouter::get('/test-output', function() {
+ TestRouter::get('/test-output', function () {
return 'return value';
});
@@ -30,8 +30,8 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
public function testUnicodeCharacters()
{
// Test spanish characters
- TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
- TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
+ TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s\-]+']);
+ TestRouter::get('/test/{param}', '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());
@@ -78,10 +78,11 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
public function testSimilarUrls()
{
// Match normal route on alias
- TestRouter::resource('/url11', 'DummyController@method1');
- TestRouter::resource('/url1', 'DummyController@method1', ['as' => 'match']);
+ TestRouter::get('/url11', 'DummyController@method1');
+ TestRouter::get('/url22', 'DummyController@method2');
+ TestRouter::get('/url33', 'DummyController@method2')->name('match');
- TestRouter::debugNoReset('/url1', 'get');
+ TestRouter::debugNoReset('/url33', 'get');
$this->assertEquals(TestRouter::getUrl('match'), TestRouter::getUrl());
@@ -170,4 +171,104 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
}
+ public function testCustomRegex()
+ {
+ TestRouter::request()->setHost('google.com');
+
+ TestRouter::get('/admin/', function () {
+ return 'match';
+ })->setMatch('/^\/admin\/?(.*)/i');
+
+ $output = TestRouter::debugOutput('/admin/asd/bec/123', 'get');
+ $this->assertEquals('match', $output);
+ }
+
+ public function testRenderMultipleRoutesDisabled()
+ {
+ TestRouter::router()->setRenderMultipleRoutes(false);
+
+ $result = false;
+
+ TestRouter::get('/', function () use (&$result) {
+ $result = true;
+ });
+
+ TestRouter::get('/', function () use (&$result) {
+ $result = false;
+ });
+
+ TestRouter::debug('/');
+
+ $this->assertTrue($result);
+ }
+
+ public function testRenderMultipleRoutesEnabled()
+ {
+ TestRouter::router()->setRenderMultipleRoutes(true);
+
+ $result = [];
+
+ TestRouter::get('/', function () use (&$result) {
+ $result[] = 'route1';
+ });
+
+ TestRouter::get('/', function () use (&$result) {
+ $result[] = 'route2';
+ });
+
+ TestRouter::debug('/');
+
+ $this->assertCount(2, $result);
+ }
+
+ public function testDefaultNamespace()
+ {
+ TestRouter::setDefaultNamespace('\\Default\\Namespace');
+
+ TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
+
+ TestRouter::group([
+ 'namespace' => 'Appended\Namespace',
+ 'prefix' => '/horses',
+ ], function () {
+
+ TestRouter::get('/', 'DummyController@method1');
+
+ TestRouter::group([
+ 'namespace' => '\\New\\Namespace',
+ 'prefix' => '/race',
+ ], function () {
+
+ TestRouter::get('/', 'DummyController@method1');
+
+ });
+ });
+
+ // Test appended namespace
+
+ $class = null;
+
+ try {
+ TestRouter::debugNoReset('/horses/');
+ } catch (\Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException $e) {
+ $class = $e->getClass();
+ }
+
+ $this->assertEquals('\\Default\\Namespace\\Appended\Namespace\\DummyController', $class);
+
+ // Test overwritten namespace
+
+ $class = null;
+
+ try {
+ TestRouter::debugNoReset('/horses/race');
+ } catch (\Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException $e) {
+ $class = $e->getClass();
+ }
+
+ $this->assertEquals('\\New\\Namespace\\DummyController', $class);
+
+ TestRouter::router()->reset();
+ }
+
}
\ No newline at end of file
diff --git a/tests/TestRouter.php b/tests/TestRouter.php
index a6a5321..1a1b4c1 100644
--- a/tests/TestRouter.php
+++ b/tests/TestRouter.php
@@ -3,6 +3,11 @@
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
{
+ public function __construct()
+ {
+ static::request()->setHost('testhost.com');
+ }
+
public static function debugNoReset($testUrl, $testMethod = 'get')
{
$request = static::request();
@@ -13,7 +18,7 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
static::start();
}
- public static function debug($testUrl, $testMethod = 'get')
+ public static function debug($testUrl, $testMethod = 'get', bool $reset = true)
{
try {
static::debugNoReset($testUrl, $testMethod);
@@ -22,19 +27,20 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
throw $e;
}
- static::router()->reset();
+ if($reset === true) {
+ static::router()->reset();
+ }
}
- public static function debugOutput($testUrl, $testMethod = 'get')
+ public static function debugOutput($testUrl, $testMethod = 'get', bool $reset = true)
{
$response = null;
// Route request
ob_start();
- static::debug($testUrl, $testMethod);
- $response = ob_get_contents();
- ob_end_clean();
+ static::debug($testUrl, $testMethod, $reset);
+ $response = ob_get_clean();
// Return response
return $response;