@@ -290,7 +281,12 @@ 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
+getInput()->get($index, $defaultValue, $methods);
+ return request()->getInputHandler()->getValue($index, $defaultValue, ...$methods);
}
- return request()->getInput();
+ return request()->getInputHandler();
}
-function redirect($url, $code = null)
+/**
+ * @param string $url
+ * @param int|null $code
+ */
+function redirect(string $url, ?int $code = null): void
{
if ($code !== null) {
response()->httpCode($code);
@@ -359,11 +360,11 @@ function redirect($url, $code = null)
* Get current csrf-token
* @return string|null
*/
-function csrf_token()
+function csrf_token(): ?string
{
$baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) {
- return $baseVerifier->getToken();
+ return $baseVerifier->getTokenProvider()->getToken();
}
return null;
@@ -661,6 +662,88 @@ 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:
@@ -791,7 +874,7 @@ class SessionTokenProvider implements ITokenProvider
/**
* Refresh existing token
*/
- public function refresh()
+ public function refresh(): void
{
// Implement your own functionality here...
}
@@ -802,7 +885,18 @@ class SessionTokenProvider implements ITokenProvider
* @param string $token
* @return bool
*/
- public function validate($token)
+ public function validate($token): bool
+ {
+ // Implement your own functionality here...
+ }
+
+ /**
+ * Get token token
+ *
+ * @param string|null $defaultValue
+ * @return string|null
+ */
+ public function getToken(?string $defaultValue = null): ?string
{
// Implement your own functionality here...
}
@@ -833,17 +927,17 @@ namespace Demo\Middlewares;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
-class CustomMiddleware implements Middleware {
-
- public function handle(Request $request) {
+class CustomMiddleware implements IMiddleware {
+ public function handle(Request $request): void
+ {
+
// Authenticate user, will be available using request()->user
$request->user = User::authenticate();
// If authentication failed, redirect request to user-login page.
if($request->user === null) {
$request->setRewriteUrl(url('user.login'));
- return $request;
}
}
@@ -869,9 +963,11 @@ The code should be placed in the file that contains your routes.
Router::get('/not-found', 'PageController@notFound');
Router::error(function(Request $request, \Exception $exception) {
- if($exception instanceof NotFoundHttpException && $exception->getCode() == 404) {
+
+ if($exception instanceof NotFoundHttpException && $exception->getCode() === 404) {
response()->redirect('/not-found');
}
+
});
```
@@ -882,18 +978,18 @@ This is a basic example of an ExceptionHandler implementation (please see "[Easi
```php
namespace Demo\Handlers;
-use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Request;
+use Pecee\SimpleRouter\Handlers\IExceptionHandler;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
class CustomExceptionHandler implements IExceptionHandler
{
- public function handleError(Request $request, \Exception $error)
+ public function handleError(Request $request, \Exception $error): void
{
/* You can use the exception handler to format errors depending on the request and type. */
- if (stripos($request->getUrl()->getPath(), '/api') !== false) {
+ if ($request->getUrl()->contains('/api')) {
response()->json([
'error' => $error->getMessage(),
@@ -906,10 +1002,9 @@ class CustomExceptionHandler implements IExceptionHandler
if($error instanceof NotFoundHttpException) {
// Render custom 404-page
-
$request->setRewriteCallback('Demo\Controllers\PageController@notFound');
- return $request;
-
+ return;
+
}
throw $error;
@@ -925,17 +1020,33 @@ class CustomExceptionHandler implements IExceptionHandler
By default all controller and resource routes will use a simplified version of their url as name.
+You easily use the `url()` shortcut helper function to retrieve urls for your routes or manipulate the current url.
+
+`url()` will return a `Url` object which will return a `string` when rendered, so it can be used safely in templates etc. but
+contains all the useful helpers methods in the `Url` class like `contains`, `indexOf` etc.
+Check the [Useful url tricks](#useful-url-tricks) below.
+
+### Get the current url
+
+It has never been easier to get and/or manipulate the current url.
+
+The example below shows you how to get the current url:
+
+```php
+# output: /current-url
+url();
+```
+
### Get by name (single route)
```php
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
+# output: /product-view/22/?category=shoes
url('product', ['id' => 22], ['category' => 'shoes']);
-url('product', null, ['category' => 'shoes']);
-# output
-# /product-view/22/?category=shoes
-# /product-view/?category=shoes
+# output: /product-view/?category=shoes
+url('product', null, ['category' => 'shoes']);
```
### Get by name (controller route)
@@ -943,14 +1054,14 @@ url('product', null, ['category' => 'shoes']);
```php
SimpleRouter::controller('/images', ImagesController::class, ['as' => 'picture']);
+# output: /images/view/?category=shows
url('picture@getView', null, ['category' => 'shoes']);
-url('picture', 'getView', ['category' => 'shoes']);
-url('picture', 'view');
-# output
-# /images/view/?category=shows
-# /images/view/?category=shows
-# /images/view/
+# output: /images/view/?category=shows
+url('picture', 'getView', ['category' => 'shoes']);
+
+# output: /images/view/
+url('picture', 'view');
```
### Get by class
@@ -959,12 +1070,11 @@ url('picture', 'view');
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
SimpleRouter::controller('/images', 'ImagesController');
+# output: /product-view/22/?category=shoes
url('ProductsController@show', ['id' => 22], ['category' => 'shoes']);
-url('ImagesController@getImage', null, ['id' => 22]);
-# output
-# /product-view/22/?category=shoes
-# /images/image/?id=22
+# output: /images/image/?id=22
+url('ImagesController@getImage', null, ['id' => 22]);
```
### Using custom names for methods on a controller/resource route
@@ -983,30 +1093,67 @@ url('gadgets.iphone');
```php
SimpleRouter::resource('/phones', PhonesController::class);
+# output: /phones/
url('phones');
+
+# output: /phones/
url('phones.index');
+
+# output: /phones/create/
url('phones.create');
+
+# output: /phones/edit/
url('phones.edit');
-
-// etc..
-
-# output
-# /phones/
-# /phones/create/
-# /phones/edit/
```
-### Get the current url
+### Manipulating url
+
+You can easily manipulate the query-strings, by adding your get param arguments.
```php
-url();
-url(null, null, ['q' => 'cars']);
+# output: /current-url?q=cars
-# output
-# /CURRENT-URL/
-# /CURRENT-URL/?q=cars
+url(null, null, ['q' => 'cars']);
```
+You can remove a query-string parameter by setting the value to `null`.
+
+The example below will remove any query-string parameter named `q` from the url but keep all others query-string parameters:
+
+```php
+$url = url()->removeParam('q');
+```
+
+For more information please check the [Useful url tricks](#useful-url-tricks) section of the documentation.
+
+### Useful url tricks
+
+Calling `url` will always return a `Url` object. Upon rendered it will return a `string` of the relative `url`, so it's safe to use in templates etc.
+
+However this allow us to use the useful methods on the `Url` object like `indexOf` and `contains` or retrieve specific parts of the url like the path, querystring parameters, host etc. You can also manipulate the url like removing- or adding parameters, changing host and more.
+
+In the example below, we check if the current url contains the `/api` part.
+
+```php
+if(url()->contains('/api')) {
+
+ // ... do stuff
+
+}
+```
+
+As mentioned earlier, you can also use the `Url` object to show specific parts of the url or control what part of the url you want.
+
+```php
+# Grab the query-string parameter id from the current-url.
+$id = url()->getParam('id');
+
+# Get the absolute url for the current url.
+$absoluteUrl = url()->getAbsoluteUrl();
+```
+
+For more available methods please check the `Pecee\Http\Url` class.
+
# Input & parameters
## Using the Input class to manage parameters
@@ -1025,18 +1172,16 @@ $value = input($index, $defaultValue, $methods);
### Get parameter object
-Will return an instance of `InputItem` or `InputFile` depending on the type.
+The example below will return an instance of `InputItem` or `InputFile` depending on the type.
You can use this in your html as it will render the value of the item.
-However if you want to compare value in your if statements, you have to use
-the `getValue` or use the `input()` instead.
+
+If you want to compare value in your if statements, you have to use the `getValue` or use the `input()` helper function instead.
If items is grouped in the html, it will return an array of items.
-**Note:** `getObject` will only return `$defaultValue` if the item doesn't exist. If you want `$defaultValue` to be returned if the item is empty, please use `input()` instead.
-
```php
-$object = input()->getObject($index, $defaultValue = null, $methods = null);
+$object = input()->get($index, $defaultValue = null, $methods = null);
```
### Return specific GET parameter (where name is the name of your parameter):
@@ -1050,7 +1195,7 @@ $object = input()->getObject($index, $defaultValue = null, $methods = null);
* $defaultValue is returned if the value is empty.
*/
-$id = input()->get($index, $defaultValue, $method);
+$id = input()->getValue($index, $defaultValue, $method);
# -- shortcut to above --
@@ -1058,15 +1203,19 @@ $id = input($index, $defaultValue, $method);
# -- match specific --
-$object = input($index, $defaultValue, 'get');
-$object = input($index, $defaultValue, 'post');
-$object = input($index, $defaultValue, 'file');
+$value = input($index, $defaultValue, 'get');
+$value = input($index, $defaultValue, 'post');
+$value = input($index, $defaultValue, 'file');
# -- or --
$object = input()->findGet($index, $defaultValue);
$object = input()->findPost($index, $defaultValue);
$object = input()->findFile($index, $defaultValue);
+
+# -- get the full object --
+
+$object = input()->get($index, 'post', 'get');
```
### Managing files
@@ -1131,6 +1280,142 @@ $siteId = input('site_id', 2, ['post', 'get']);
---
+# Events
+
+This section will help you understand how to register your own callbacks to events in the router.
+It will also cover the basics of event-handlers; how to use the handlers provided with the router and how to create your own custom event-handlers.
+
+## Available events
+
+This section contains all available events that can be registered using the `EventHandler`.
+
+All event callbacks will retrieve a `EventArgument` object as parameter. This object contains easy access to event-name, router- and request instance and any special event-arguments related to the given event. You can see what special event arguments each event returns in the list below.
+
+| Name | Special arguments | Description |
+| ------------- |----------- | ---- |
+| `EVENT_ALL` | - | Fires when a event is triggered. |
+| `EVENT_INIT` | - | Fires when router is initializing and before routes are loaded. |
+| `EVENT_LOAD` | `loadedRoutes` | Fires when all routes has been loaded and rendered, just before the output is returned. |
+| `EVENT_ADD_ROUTE` | `route` | Fires when route is added to the router. |
+| `EVENT_REWRITE` | `rewriteUrl`
`rewriteRoute` | Fires when a url-rewrite is and just before the routes are re-initialized. |
+| `EVENT_BOOT` | `bootmanagers` | Fires when the router is booting. This happens just before boot-managers are rendered and before any routes has been loaded. |
+| `EVENT_RENDER_BOOTMANAGER` | `bootmanagers`
`bootmanager` | Fires before a boot-manager is rendered. |
+| `EVENT_LOAD_ROUTES` | `routes` | Fires when the router is about to load all routes. |
+| `EVENT_FIND_ROUTE` | `name` | Fires whenever the `findRoute` method is called within the `Router`. This usually happens when the router tries to find routes that contains a certain url, usually after the `EventHandler::EVENT_GET_URL` event. |
+| `EVENT_GET_URL` | `name`
`parameters`
`getParams` | Fires whenever the `Router::getUrl` method or `url`-helper function is called and the router tries to find the route. |
+| `EVENT_MATCH_ROUTE` | `route` | Fires when a route is matched and valid (correct request-type etc). and before the route is rendered. |
+| `EVENT_RENDER_ROUTE` | `route` | Fires before a route is rendered. |
+| `EVENT_LOAD_EXCEPTIONS` | `exception`
`exceptionHandlers` | Fires when the router is loading exception-handlers. |
+| `EVENT_RENDER_EXCEPTION` | `exception`
`exceptionHandler`
`exceptionHandlers` | Fires before the router is rendering a exception-handler. |
+| `EVENT_RENDER_MIDDLEWARES` | `route`
`middlewares` | Fires before middlewares for a route is rendered. |
+| `EVENT_RENDER_CSRF` | `csrfVerifier` | Fires before the CSRF-verifier is rendered. |
+
+## Registering new event
+
+To register a new event you need to create a new instance of the `EventHandler` object. On this object you can add as many callbacks as you like by calling the `registerEvent` method.
+
+When you've registered events, make sure to add it to the router by calling
+`SimpleRouter::addEventHandler()`. We recommend that you add your event-handlers within your `routes.php`.
+
+**Example:**
+
+```php
+use Pecee\SimpleRouter\Handlers\EventHandler;
+use Pecee\SimpleRouter\Event\EventArgument;
+
+// --- your routes goes here ---
+
+$eventHandler = new EventHandler();
+
+// Add event that fires when a route is rendered
+$eventHandler->register(EventHandler::EVENT_RENDER_ROUTE, function(EventArgument $argument) {
+
+ // Get the route by using the special argument for this event.
+ $route = $argument->route;
+
+ // DO STUFF...
+
+});
+
+SimpleRouter::addEventHandler($eventHandler);
+
+```
+
+## Custom EventHandlers
+
+`EventHandler` is the class that manages events and must inherit from the `IEventHandler` interface. The handler knows how to handle events for the given handler-type.
+
+Most of the time the basic `\Pecee\SimpleRouter\Handler\EventHandler` class will be more than enough for most people as you simply register an event which fires when triggered.
+
+Let's go over how to create your very own event-handler class.
+
+Below is a basic example of a custom event-handler called `DatabaseDebugHandler`. The idea of the sample below is to logs all events to the database when triggered. Hopefully it will be enough to give you an idea on how the event-handlers work.
+
+```php
+namespace Demo\Handlers;
+
+use Pecee\SimpleRouter\Event\EventArgument;
+use Pecee\SimpleRouter\Router;
+
+class DatabaseDebugHandler implements IEventHandler
+{
+
+ /**
+ * Debug callback
+ * @var \Closure
+ */
+ protected $callback;
+
+ public function __construct()
+ {
+ $this->callback = function (EventArgument $argument) {
+ // todo: store log in database
+ };
+ }
+
+ /**
+ * Get events.
+ *
+ * @param string|null $name Filter events by name.
+ * @return array
+ */
+ public function getEvents(?string $name): array
+ {
+ return [
+ $name => [
+ $this->callback,
+ ],
+ ];
+ }
+
+ /**
+ * Fires any events registered with given event-name
+ *
+ * @param Router $router Router instance
+ * @param string $name Event name
+ * @param array ...$eventArgs Event arguments
+ */
+ public function fireEvents(Router $router, string $name, ...$eventArgs): void
+ {
+ $callback = $this->callback;
+ $callback(new EventArgument($router, $eventArgs));
+ }
+
+ /**
+ * Set debug callback
+ *
+ * @param \Closure $event
+ */
+ public function setCallback(\Closure $event): void
+ {
+ $this->callback = $event;
+ }
+
+}
+```
+
+---
+
# Advanced
## Url rewriting
@@ -1161,10 +1446,19 @@ To interfere with the router, we create a class that implements the ```IRouterBo
```php
use Pecee\Http\Request;
use Pecee\SimpleRouter\IRouterBootManager;
+use Pecee\SimpleRouter\Router;
-class CustomRouterRules implement IRouterBootManager {
+class CustomRouterRules implement IRouterBootManager
+{
- public function boot(Request $request) {
+ /**
+ * Called when router is booting and before the routes is loaded.
+ *
+ * @param \Pecee\SimpleRouter\Router $router
+ * @param \Pecee\Http\Request $request
+ */
+ public function boot(\Pecee\SimpleRouter\Router $router, \Pecee\Http\Request $request): void
+ {
$rewriteRules = [
'/my-cat-is-beatiful' => '/article/view/1',
@@ -1258,6 +1552,219 @@ class Router extends SimpleRouter {
---
+# Help and support
+
+This section will go into details on how to debug the router and answer some of the commonly asked questions- and issues.
+
+## Common issues and fixes
+
+This section will go over common issues and how to resolve them.
+
+## Debugging
+
+This section will show you how to write unit-tests for the router, view useful debugging information and answer some of the frequently asked questions.
+
+It will also covers how to report any issue you might encounter.
+
+### Creating unit-tests
+
+The easiest and fastest way to debug any issues with the router, is to create a unit-test that represents the issue you are experiencing.
+
+Unit-tests use a special `TestRouter` class, which simulates a request-method and requested url of a browser.
+
+The `TestRouter` class can return the output directly or render a route silently.
+
+```php
+public function testUnicodeCharacters()
+{
+ // Add route containing two optional paramters with special spanish characters like "í".
+ TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
+
+ // Start the routing and simulate the url "/cursos/listado/especialidad/cirugía local".
+ TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'GET');
+
+ // Verify that the url for the loaded route matches the expected route.
+ $this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
+
+ // Start the routing and simulate the url "/test/Dermatología" using "GET" as request-method.
+ TestRouter::debugNoReset('/test/Dermatología', 'GET');
+
+ // Another route containing one parameter with special spanish characters like "í".
+ TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
+
+ // Get all parameters parsed by the loaded route.
+ $parameters = TestRouter::request()->getLoadedRoute()->getParameters();
+
+ // Check that the parameter named "param" matches the exspected value.
+ $this->assertEquals('Dermatología', $parameters['param']);
+
+ // Add route testing danish special characters like "ø".
+ TestRouter::get('/category/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
+
+ // Start the routing and simulate the url "/kategory/økse" using "GET" as request-method.
+ TestRouter::debugNoReset('/category/økse', 'GET');
+
+ // Validate that the URL of the loaded-route matches the expected url.
+ $this->assertEquals('/category/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
+
+ // Reset the router, so other tests wont inherit settings or the routes we've added.
+ TestRouter::router()->reset();
+}
+```
+
+#### Using the TestRouter helper
+
+Depending on your test, you can use the methods below when rendering routes in your unit-tests.
+
+
+| Method | Description |
+| ------------- |-------------|
+| ```TestRouter::debug($url, $method)``` | Will render the route without returning anything. Exceptions will be thrown and the router will be reset automatically. |
+| ```TestRouter::debugOutput($url, $method)``` | Will render the route and return any value that the route might output. Manual reset required by calling `TestRouter::router()->reset()`. |
+| ```TestRouter::debugNoReset($url, $method);``` | Will render the route without resetting the router. Useful if you need to get loaded route, parameters etc. from the router. Manual reset required by calling `TestRouter::router()->reset()`. |
+
+### Debug information
+
+The library can output debug-information, which contains information like loaded routes, the parsed request-url etc. It also contains info which are important when reporting a new issue like PHP-version, library version, server-variables, router debug log etc.
+
+You can activate the debug-information by calling the alternative start-method.
+
+The example below will start the routing an return array with debugging-information
+
+**Example:**
+
+```php
+$debugInfo = SimpleRouter::startDebug();
+echo sprintf('%s
', var_export($debugInfo));
+exit;
+```
+
+**The example above will provide you with an output containing:**
+
+| Key | Description |
+| ------------- |------------- |
+| `url` | The parsed request-uri. This url should match the url in the browser.|
+| `method` | The browsers request method (example: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` etc).|
+| `host` | The website host (example: `domain.com`).|
+| `loaded_routes` | List of all the routes that matched the `url` and that has been rendered/loaded. |
+| `all_routes` | All available routes |
+| `boot_managers` | All available BootManagers |
+| `csrf_verifier` | CsrfVerifier class |
+| `log` | List of debug messages/log from the router. |
+| `router_output` | The rendered callback output from the router. |
+| `library_version` | The version of simple-php-router you are using. |
+| `php_version` | The version of PHP you are using. |
+| `server_params` | List of all `$_SERVER` variables/headers. |
+
+#### Benchmark and logging
+
+You can activate benchmark debugging/logging by calling `setDebugEnabled` method on the `Router` instance.
+
+You have to enable debugging BEFORE starting the routing.
+
+**Example:**
+
+```php
+SimpleRouter::router()->setDebugEnabled(true);
+SimpleRouter::start();
+```
+
+When the routing is complete, you can get the debug-log by calling the `getDebugLog()` on the `Router` instance. This will return an `array` of log-messages each containing execution time, trace info and debug-message.
+
+**Example:**
+
+```php
+$messages = SimpleRouter::router()->getDebugLog();
+```
+
+## Reporting a new issue
+
+**Before reporting your issue, make sure that the issue you are experiencing aren't already answered in the [Common errors](#common-errors) section or by searching the [closed issues](https://github.com/skipperbent/simple-php-router/issues?q=is%3Aissue+is%3Aclosed) page on GitHub.**
+
+To avoid confusion and to help you resolve your issue as quickly as possible, you should provide a detailed explanation of the problem you are experiencing.
+
+### Procedure for reporting a new issue
+
+1. Go to [this page](https://github.com/skipperbent/simple-php-router/issues/new) to create a new issue.
+2. Add a title that describes your problems in as few words as possible.
+3. Copy and paste the template below in the description of your issue and replace each step with your own information. If the step is not relevant for your issue you can delete it.
+
+### Issue template
+
+Copy and paste the template below into the description of your new issue and replace it with your own information.
+
+You can check the [Debug information](#debug-information) section to see how to generate the debug-info.
+
+
+### Description
+
+The library fails to render the route `/user/æsel` which contains one parameter using a custom regular expression for matching special foreign characters. Routes without special characters like `/user/tom` renders correctly.
+
+### Steps to reproduce the error
+
+1. Add the following route:
+
+```php
+SimpleRouter::get('/user/{name}', 'UserController@show')->where(['name' => '[\w]+']);
+```
+
+2. Navigate to `/user/æsel` in browser.
+
+3. `NotFoundHttpException` is thrown by library.
+
+### Route and/or callback for failing route
+
+*Route:*
+
+```php
+SimpleRouter::get('/user/{name}', 'UserController@show')->where(['name' => '[\w]+']);
+```
+
+*Callback:*
+
+```php
+public function show($username) {
+ return sprintf('Username is: %s', $username);
+}
+```
+
+### Debug info
+
+```php
+
+[PASTE YOUR DEBUG-INFO HERE]
+
+```
+
+
+Remember that a more detailed issue- description and debug-info might suck to write, but it will help others understand- and resolve your issue without asking for the information.
+
+**Note:** please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue. Providing the necessary steps to reproduce the error within your description, adding useful debugging info etc. will help others quickly resolve the issue you are reporting.
+
+## Feedback and development
+
+If the library is missing a feature that you need in your project or if you have feedback, we'd love to hear from you.
+Feel free to leave us feedback by [creating a new issue](https://github.com/skipperbent/simple-php-router/issues/new).
+
+**Experiencing an issue?**
+
+Please refer to our [Help and support](#help-and-support) section in the documentation before reporting a new issue.
+
+### Contribution development guidelines
+
+- Please try to follow the PSR-2 codestyle guidelines.
+
+- Please create your pull requests to the development base that matches the version number you want to change.
+For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
+
+- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
+
+- When changing existing functionality, please ensure that the unit-tests working.
+
+- When adding new stuff, please remember to add new unit-tests for the functionality.
+
+---
+
# Credits
## Sites
diff --git a/composer.json b/composer.json
index 2fee7b4..d0af205 100644
--- a/composer.json
+++ b/composer.json
@@ -27,14 +27,16 @@
}
],
"require": {
- "php": ">=5.4.0"
+ "php": ">=7.1",
+ "php-di/php-di": "^6.0"
},
"require-dev": {
- "phpunit/phpunit": "4.7.7"
+ "phpunit/phpunit": "^6.0",
+ "mockery/mockery": "^1"
},
"autoload": {
"psr-4": {
"Pecee\\": "src/Pecee/"
}
}
-}
\ No newline at end of file
+}
diff --git a/helpers.php b/helpers.php
index 71ae2fb..00ffa4b 100644
--- a/helpers.php
+++ b/helpers.php
@@ -1,6 +1,9 @@
getInput()->get($index, $defaultValue, $methods);
+ return request()->getInputHandler()->getValue($index, $defaultValue, ...$methods);
}
- return request()->getInput();
+ return request()->getInputHandler();
}
-function redirect($url, $code = null)
+/**
+ * @param string $url
+ * @param int|null $code
+ */
+function redirect(string $url, ?int $code = null): void
{
if ($code !== null) {
response()->httpCode($code);
@@ -70,7 +77,7 @@ function redirect($url, $code = null)
* Get current csrf-token
* @return string|null
*/
-function csrf_token()
+function csrf_token(): ?string
{
$baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) {
diff --git a/phpunit.xml b/phpunit.xml
new file mode 100644
index 0000000..6e8f0c6
--- /dev/null
+++ b/phpunit.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+ tests/Pecee/SimpleRouter/
+
+
+
+
+ src
+
+
+
diff --git a/src/Pecee/Controllers/IResourceController.php b/src/Pecee/Controllers/IResourceController.php
index 502017f..5900467 100644
--- a/src/Pecee/Controllers/IResourceController.php
+++ b/src/Pecee/Controllers/IResourceController.php
@@ -1,47 +1,48 @@
index = $index;
@@ -31,7 +31,7 @@ class InputFile implements IInputItem
* @throws InvalidArgumentException
* @return static
*/
- public static function createFromArray(array $values)
+ public static function createFromArray(array $values): self
{
if (isset($values['index']) === false) {
throw new InvalidArgumentException('Index key is required');
@@ -48,8 +48,8 @@ class InputFile implements IInputItem
];
return (new static($values['index']))
- ->setSize($values['size'])
- ->setError($values['error'])
+ ->setSize((int)$values['size'])
+ ->setError((int)$values['error'])
->setType($values['type'])
->setTmpName($values['tmp_name'])
->setFilename($values['name']);
@@ -59,7 +59,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
- public function getIndex()
+ public function getIndex(): string
{
return $this->index;
}
@@ -67,9 +67,9 @@ class InputFile implements IInputItem
/**
* Set input index
* @param string $index
- * @return static $this
+ * @return static
*/
- public function setIndex($index)
+ public function setIndex(string $index): IInputItem
{
$this->index = $index;
@@ -79,7 +79,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
- public function getSize()
+ public function getSize(): string
{
return $this->size;
}
@@ -87,9 +87,9 @@ class InputFile implements IInputItem
/**
* Set file size
* @param int $size
- * @return static $this
+ * @return static
*/
- public function setSize($size)
+ public function setSize(int $size): IInputItem
{
$this->size = $size;
@@ -100,7 +100,7 @@ class InputFile implements IInputItem
* Get mime-type of file
* @return string
*/
- public function getMime()
+ public function getMime(): string
{
return $this->getType();
}
@@ -108,7 +108,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
- public function getType()
+ public function getType(): string
{
return $this->type;
}
@@ -116,9 +116,9 @@ class InputFile implements IInputItem
/**
* Set type
* @param string $type
- * @return static $this
+ * @return static
*/
- public function setType($type)
+ public function setType(string $type): IInputItem
{
$this->type = $type;
@@ -130,7 +130,7 @@ class InputFile implements IInputItem
*
* @return string
*/
- public function getExtension()
+ public function getExtension(): string
{
return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
}
@@ -140,7 +140,7 @@ class InputFile implements IInputItem
*
* @return string
*/
- public function getName()
+ public function getName(): ?string
{
return $this->name;
}
@@ -150,9 +150,9 @@ class InputFile implements IInputItem
* Useful for adding validation etc.
*
* @param string $name
- * @return static $this
+ * @return static
*/
- public function setName($name)
+ public function setName(string $name): IInputItem
{
$this->name = $name;
@@ -163,9 +163,9 @@ class InputFile implements IInputItem
* Set filename
*
* @param string $name
- * @return static $this
+ * @return static
*/
- public function setFilename($name)
+ public function setFilename($name): IInputItem
{
$this->filename = $name;
@@ -177,7 +177,7 @@ class InputFile implements IInputItem
*
* @return string mixed
*/
- public function getFilename()
+ public function getFilename(): ?string
{
return $this->filename;
}
@@ -188,7 +188,7 @@ class InputFile implements IInputItem
* @param string $destination
* @return bool
*/
- public function move($destination)
+ public function move($destination): bool
{
return move_uploaded_file($this->tmpName, $destination);
}
@@ -198,7 +198,7 @@ class InputFile implements IInputItem
*
* @return string
*/
- public function getContents()
+ public function getContents(): string
{
return file_get_contents($this->tmpName);
}
@@ -208,7 +208,7 @@ class InputFile implements IInputItem
*
* @return bool
*/
- public function hasError()
+ public function hasError(): bool
{
return ($this->getError() !== 0);
}
@@ -216,20 +216,20 @@ class InputFile implements IInputItem
/**
* Get upload-error code.
*
- * @return string
+ * @return int
*/
- public function getError()
+ public function getError(): int
{
- return $this->errors;
+ return (int)$this->errors;
}
/**
* Set error
*
* @param int $error
- * @return static $this
+ * @return static
*/
- public function setError($error)
+ public function setError($error): IInputItem
{
$this->errors = (int)$error;
@@ -239,7 +239,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
- public function getTmpName()
+ public function getTmpName(): string
{
return $this->tmpName;
}
@@ -247,21 +247,21 @@ class InputFile implements IInputItem
/**
* Set file temp. name
* @param string $name
- * @return static $this
+ * @return static
*/
- public function setTmpName($name)
+ public function setTmpName($name): IInputItem
{
$this->tmpName = $name;
return $this;
}
- public function __toString()
+ public function __toString(): string
{
return $this->getTmpName();
}
- public function getValue()
+ public function getValue(): ?string
{
return $this->getFilename();
}
@@ -270,14 +270,14 @@ class InputFile implements IInputItem
* @param string $value
* @return static
*/
- public function setValue($value)
+ public function setValue(string $value): IInputItem
{
$this->filename = $value;
return $this;
}
- public function toArray()
+ public function toArray(): array
{
return [
'tmp_name' => $this->tmpName,
diff --git a/src/Pecee/Http/Input/Input.php b/src/Pecee/Http/Input/InputHandler.php
similarity index 69%
rename from src/Pecee/Http/Input/Input.php
rename to src/Pecee/Http/Input/InputHandler.php
index b40dfef..028f9ec 100644
--- a/src/Pecee/Http/Input/Input.php
+++ b/src/Pecee/Http/Input/InputHandler.php
@@ -5,7 +5,7 @@ namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Request;
-class Input
+class InputHandler
{
/**
* @var array
@@ -42,26 +42,26 @@ class Input
* Parse input values
*
*/
- public function parseInputs()
+ public function parseInputs(): void
{
/* Parse get requests */
- if (count($_GET) !== 0) {
+ if (\count($_GET) !== 0) {
$this->get = $this->handleGetPost($_GET);
}
/* Parse post requests */
$postVars = $_POST;
- if (in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
+ if (\in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
- if (count($postVars) !== 0) {
+ if (\count($postVars) !== 0) {
$this->post = $this->handleGetPost($postVars);
}
/* Parse get requests */
- if (count($_FILES) !== 0) {
+ if (\count($_FILES) !== 0) {
$this->file = $this->parseFiles();
}
}
@@ -69,25 +69,24 @@ class Input
/**
* @return array
*/
- public function parseFiles()
+ public function parseFiles(): array
{
$list = [];
foreach ((array)$_FILES as $key => $value) {
// Handle array input
- if (is_array($value['name']) === false) {
+ if (\is_array($value['name']) === false) {
$values['index'] = $key;
try {
$list[$key] = InputFile::createFromArray($values + $value);
- } catch(InvalidArgumentException $e ){
+ } catch (InvalidArgumentException $e) {
}
continue;
}
$keys = [$key];
-
$files = $this->rearrangeFiles($value['name'], $keys, $value);
if (isset($list[$key]) === true) {
@@ -101,7 +100,7 @@ class Input
return $list;
}
- protected function rearrangeFiles(array $values, &$index, $original)
+ protected function rearrangeFiles(array $values, &$index, $original): array
{
$originalIndex = $index[0];
@@ -111,7 +110,7 @@ class Input
foreach ($values as $key => $value) {
- if (is_array($original['name'][$key]) === false) {
+ if (\is_array($original['name'][$key]) === false) {
try {
@@ -132,7 +131,7 @@ class Input
$output[$key] = $file;
continue;
- } catch(InvalidArgumentException $e) {
+ } catch (InvalidArgumentException $e) {
}
}
@@ -152,14 +151,14 @@ class Input
return $output;
}
- protected function handleGetPost(array $array)
+ protected function handleGetPost(array $array): array
{
$list = [];
foreach ($array as $key => $value) {
// Handle array input
- if (is_array($value) === false) {
+ if (\is_array($value) === false) {
$list[$key] = new InputItem($key, $value);
continue;
}
@@ -179,9 +178,9 @@ class Input
* @param string|null $defaultValue
* @return InputItem|string
*/
- public function findPost($index, $defaultValue = null)
+ public function findPost(string $index, ?string $defaultValue = null)
{
- return isset($this->post[$index]) ? $this->post[$index] : $defaultValue;
+ return $this->post[$index] ?? $defaultValue;
}
/**
@@ -191,9 +190,9 @@ class Input
* @param string|null $defaultValue
* @return InputFile|string
*/
- public function findFile($index, $defaultValue = null)
+ public function findFile(string $index, ?string $defaultValue = null)
{
- return isset($this->file[$index]) ? $this->file[$index] : $defaultValue;
+ return $this->file[$index] ?? $defaultValue;
}
/**
@@ -203,40 +202,35 @@ class Input
* @param string|null $defaultValue
* @return InputItem|string
*/
- public function findGet($index, $defaultValue = null)
+ public function findGet(string $index, ?string $defaultValue = null)
{
- return isset($this->get[$index]) ? $this->get[$index] : $defaultValue;
+ return $this->get[$index] ?? $defaultValue;
}
/**
* Get input object
*
* @param string $index
- * @param string|null $defaultValue
- * @param array|string|null $methods
- * @return IInputItem|string
+ * @param array ...$methods
+ * @return IInputItem|null
*/
- public function getObject($index, $defaultValue = null, $methods = null)
+ public function get(string $index, ...$methods): ?IInputItem
{
- if ($methods !== null && is_string($methods) === true) {
- $methods = [$methods];
- }
-
$element = null;
- if ($methods === null || in_array('get', $methods, false) === true) {
+ if (\count($methods) === 0 || \in_array('get', $methods, true) === true) {
$element = $this->findGet($index);
}
- if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods, false) === true)) {
+ if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array('post', $methods, true) === true)) {
$element = $this->findPost($index);
}
- if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods, false) === true)) {
+ if (($element === null && \count($methods) === 0) || (\count($methods) !== 0 && \in_array('file', $methods, true) === true)) {
$element = $this->findFile($index);
}
- return ($element !== null) ? $element : $defaultValue;
+ return $element;
}
/**
@@ -244,29 +238,25 @@ class Input
*
* @param string $index
* @param string|null $defaultValue
- * @param array|string|null $methods
- * @return InputItem|string
+ * @param array ...$methods
+ * @return string
*/
- public function get($index, $defaultValue = null, $methods = null)
+ public function getValue(string $index, ?string $defaultValue = null, ...$methods): ?string
{
- $input = $this->getObject($index, $defaultValue, $methods);
-
- if ($input instanceof InputItem) {
- return (trim($input->getValue()) === '') ? $defaultValue : $input->getValue();
- }
-
- return $input;
+ $input = $this->get($index, ...$methods);
+ return ($input === null || ($input !== null && trim($input->getValue()) === '')) ? $defaultValue : $input->getValue();
}
/**
* Check if a input-item exist
*
* @param string $index
+ * @param array ...$methods
* @return bool
*/
- public function exists($index)
+ public function exists(string $index, ...$methods): bool
{
- return ($this->getObject($index) !== null);
+ return $this->get($index, ...$methods) !== null;
}
/**
@@ -274,14 +264,18 @@ class Input
* @param array|null $filter Only take items in filter
* @return array
*/
- public function all(array $filter = null)
+ public function all(array $filter = null): array
{
- $output = $_GET + $_POST;
+ $output = $_GET;
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) {
diff --git a/src/Pecee/Http/Input/InputItem.php b/src/Pecee/Http/Input/InputItem.php
index 7ca4b93..6c677b8 100644
--- a/src/Pecee/Http/Input/InputItem.php
+++ b/src/Pecee/Http/Input/InputItem.php
@@ -8,7 +8,7 @@ class InputItem implements IInputItem
public $name;
public $value;
- public function __construct($index, $value = null)
+ public function __construct(string $index, ?string $value = null)
{
$this->index = $index;
$this->value = $value;
@@ -20,12 +20,12 @@ class InputItem implements IInputItem
/**
* @return string
*/
- public function getIndex()
+ public function getIndex(): string
{
return $this->index;
}
- public function setIndex($index)
+ public function setIndex(string $index): IInputItem
{
$this->index = $index;
@@ -35,7 +35,7 @@ class InputItem implements IInputItem
/**
* @return string
*/
- public function getName()
+ public function getName(): ?string
{
return $this->name;
}
@@ -43,9 +43,9 @@ class InputItem implements IInputItem
/**
* Set input name
* @param string $name
- * @return static $this
+ * @return static
*/
- public function setName($name)
+ public function setName(string $name): IInputItem
{
$this->name = $name;
@@ -55,7 +55,7 @@ class InputItem implements IInputItem
/**
* @return string
*/
- public function getValue()
+ public function getValue(): ?string
{
return $this->value;
}
@@ -63,16 +63,16 @@ class InputItem implements IInputItem
/**
* Set input value
* @param string $value
- * @return static $this
+ * @return static
*/
- public function setValue($value)
+ public function setValue(string $value): IInputItem
{
$this->value = $value;
return $this;
}
- public function __toString()
+ public function __toString(): string
{
return (string)$this->value;
}
diff --git a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php
index 67e57dd..7116cd7 100644
--- a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php
+++ b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php
@@ -9,8 +9,8 @@ use Pecee\Http\Security\ITokenProvider;
class BaseCsrfVerifier implements IMiddleware
{
- const POST_KEY = 'csrf-token';
- const HEADER_KEY = 'X-CSRF-TOKEN';
+ public const POST_KEY = 'csrf-token';
+ public const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $tokenProvider;
@@ -29,21 +29,21 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request
* @return bool
*/
- protected function skip(Request $request)
+ protected function skip(Request $request): bool
{
- if ($this->except === null || count($this->except) === 0) {
+ if ($this->except === null || \count($this->except) === 0) {
return false;
}
- $max = count($this->except) - 1;
+ $max = \count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
$url = rtrim($url, '/');
- if ($url[strlen($url) - 1] === '*') {
+ if ($url[\strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
- $skip = (stripos($request->getUrl()->getOriginalUrl(), $url) === 0);
+ $skip = $request->getUrl()->contains($url);
} else {
$skip = ($url === $request->getUrl()->getOriginalUrl());
}
@@ -62,19 +62,18 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request
* @throws TokenMismatchException
*/
- public function handle(Request $request)
+ public function handle(Request $request): void
{
- if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) {
+ if ($this->skip($request) === false && \in_array($request->getMethod(), ['post', 'put', 'delete'], true) === true) {
- $token = $request->getInput()->get(static::POST_KEY, null, 'post');
+ $token = $request->getInputHandler()->getValue(
+ static::POST_KEY,
+ $request->getHeader(static::HEADER_KEY),
+ 'post'
+ );
- // If the token is not posted, check headers for valid x-csrf-token
- if ($token === null) {
- $token = $request->getHeader(static::HEADER_KEY);
- }
-
- if ($this->tokenProvider->validate($token) === false) {
+ if ($this->tokenProvider->validate((string)$token) === false) {
throw new TokenMismatchException('Invalid CSRF-token.');
}
@@ -85,7 +84,7 @@ class BaseCsrfVerifier implements IMiddleware
}
- public function getTokenProvider()
+ public function getTokenProvider(): ITokenProvider
{
return $this->tokenProvider;
}
@@ -94,7 +93,7 @@ class BaseCsrfVerifier implements IMiddleware
* Set token provider
* @param ITokenProvider $provider
*/
- public function setTokenProvider(ITokenProvider $provider)
+ public function setTokenProvider(ITokenProvider $provider): void
{
$this->tokenProvider = $provider;
}
diff --git a/src/Pecee/Http/Middleware/Exceptions/TokenMismatchException.php b/src/Pecee/Http/Middleware/Exceptions/TokenMismatchException.php
index 8f21c9e..7e07c7a 100644
--- a/src/Pecee/Http/Middleware/Exceptions/TokenMismatchException.php
+++ b/src/Pecee/Http/Middleware/Exceptions/TokenMismatchException.php
@@ -1,4 +1,5 @@
parseHeaders();
- $this->setHost($this->getHeader('http-host'));
-
- // Check if special IIS header exist, otherwise use default.
- $this->setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri')));
-
- $this->input = new Input($this);
- $this->method = strtolower($this->input->get('_method', $this->getHeader('request-method')));
- }
-
- protected function parseHeaders()
- {
- $this->headers = [];
-
foreach ($_SERVER as $key => $value) {
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $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->inputHandler = new InputHandler($this);
+ $this->method = strtolower($this->inputHandler->getValue('_method', $this->getHeader('request-method')));
}
- public function isSecure()
+ public function isSecure(): bool
{
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443;
}
@@ -64,23 +97,33 @@ class Request
/**
* @return Url
*/
- public function getUrl()
+ public function getUrl(): Url
{
return $this->url;
}
/**
- * @return string
+ * Copy url object
+ *
+ * @return Url
*/
- public function getHost()
+ public function getUrlCopy(): Url
+ {
+ return clone $this->url;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getHost(): ?string
{
return $this->host;
}
/**
- * @return string
+ * @return string|null
*/
- public function getMethod()
+ public function getMethod(): ?string
{
return $this->method;
}
@@ -89,7 +132,7 @@ class Request
* Get http basic auth user
* @return string|null
*/
- public function getUser()
+ public function getUser(): ?string
{
return $this->getHeader('php-auth-user');
}
@@ -98,7 +141,7 @@ class Request
* Get http basic auth password
* @return string|null
*/
- public function getPassword()
+ public function getPassword(): ?string
{
return $this->getHeader('php-auth-pw');
}
@@ -107,16 +150,16 @@ class Request
* Get all headers
* @return array
*/
- public function getHeaders()
+ public function getHeaders(): array
{
return $this->headers;
}
/**
* Get id address
- * @return string
+ * @return string|null
*/
- public function getIp()
+ public function getIp(): ?string
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
@@ -133,27 +176,27 @@ class Request
* Get remote address/ip
*
* @alias static::getIp
- * @return string
+ * @return string|null
*/
- public function getRemoteAddr()
+ public function getRemoteAddr(): ?string
{
return $this->getIp();
}
/**
* Get referer
- * @return string
+ * @return string|null
*/
- public function getReferer()
+ public function getReferer(): ?string
{
return $this->getHeader('http-referer');
}
/**
* Get user agent
- * @return string
+ * @return string|null
*/
- public function getUserAgent()
+ public function getUserAgent(): ?string
{
return $this->getHeader('http-user-agent');
}
@@ -166,18 +209,18 @@ class Request
*
* @return string|null
*/
- public function getHeader($name, $defaultValue = null)
+ public function getHeader($name, $defaultValue = null): ?string
{
- return isset($this->headers[strtolower($name)]) ? $this->headers[strtolower($name)] : $defaultValue;
+ return $this->headers[strtolower($name)] ?? $defaultValue;
}
/**
* Get input class
- * @return Input
+ * @return InputHandler
*/
- public function getInput()
+ public function getInputHandler(): InputHandler
{
- return $this->input;
+ return $this->inputHandler;
}
/**
@@ -187,9 +230,9 @@ class Request
*
* @return bool
*/
- public function isFormatAccepted($format)
+ public function isFormatAccepted($format): bool
{
- return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
+ return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) !== false);
}
/**
@@ -197,7 +240,7 @@ class Request
*
* @return bool
*/
- public function isAjax()
+ public function isAjax(): bool
{
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
}
@@ -206,24 +249,27 @@ class Request
* Get accept formats
* @return array
*/
- public function getAcceptFormats()
+ public function getAcceptFormats(): array
{
return explode(',', $this->getHeader('http-accept'));
}
/**
- * @param string|Url $url
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
+ * @param Url $url
*/
- public function setUrl($url)
+ public function setUrl(Url $url): void
{
- $this->url = ($url instanceof Url) ? $url : new Url($url);
+ $this->url = $url;
+
+ if ($this->url->getHost() === null) {
+ $this->url->setHost((string)$this->getHost());
+ }
}
/**
- * @param string $host
+ * @param string|null $host
*/
- public function setHost($host)
+ public function setHost(?string $host): void
{
$this->host = $host;
}
@@ -231,7 +277,7 @@ class Request
/**
* @param string $method
*/
- public function setMethod($method)
+ public function setMethod(string $method): void
{
$this->method = $method;
}
@@ -242,9 +288,9 @@ class Request
* @param ILoadableRoute $route
* @return static
*/
- public function setRewriteRoute(ILoadableRoute $route)
+ public function setRewriteRoute(ILoadableRoute $route): self
{
- $this->hasRewrite = true;
+ $this->hasPendingRewrite = true;
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
return $this;
@@ -255,7 +301,7 @@ class Request
*
* @return ILoadableRoute|null
*/
- public function getRewriteRoute()
+ public function getRewriteRoute(): ?ILoadableRoute
{
return $this->rewriteRoute;
}
@@ -263,9 +309,9 @@ class Request
/**
* Get rewrite url
*
- * @return string
+ * @return string|null
*/
- public function getRewriteUrl()
+ public function getRewriteUrl(): ?string
{
return $this->rewriteUrl;
}
@@ -276,9 +322,9 @@ class Request
* @param string $rewriteUrl
* @return static
*/
- public function setRewriteUrl($rewriteUrl)
+ public function setRewriteUrl(string $rewriteUrl): self
{
- $this->hasRewrite = true;
+ $this->hasPendingRewrite = true;
$this->rewriteUrl = rtrim($rewriteUrl, '/') . '/';
return $this;
@@ -286,12 +332,12 @@ class Request
/**
* Set rewrite callback
- * @param string $callback
+ * @param string|\Closure $callback
* @return static
*/
- public function setRewriteCallback($callback)
+ public function setRewriteCallback($callback): self
{
- $this->hasRewrite = true;
+ $this->hasPendingRewrite = true;
return $this->setRewriteRoute(new RouteUrl($this->getUrl()->getPath(), $callback));
}
@@ -300,44 +346,73 @@ class Request
* Get loaded route
* @return ILoadableRoute|null
*/
- public function getLoadedRoute()
+ public function getLoadedRoute(): ?ILoadableRoute
{
- return $this->loadedRoute;
+ return (\count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
}
/**
- * Set loaded route
+ * Get all loaded routes
+ *
+ * @return array
+ */
+ public function getLoadedRoutes(): array
+ {
+ return $this->loadedRoutes;
+ }
+
+ /**
+ * Set loaded routes
+ *
+ * @param array $routes
+ * @return static
+ */
+ public function setLoadedRoutes(array $routes): self
+ {
+ $this->loadedRoutes = $routes;
+
+ return $this;
+ }
+
+ /**
+ * Added loaded route
*
* @param ILoadableRoute $route
* @return static
*/
- public function setLoadedRoute(ILoadableRoute $route)
+ public function addLoadedRoute(ILoadableRoute $route): self
{
- $this->loadedRoute = $route;
+ $this->loadedRoutes[] = $route;
return $this;
}
- public function hasRewrite()
+ /**
+ * Returns true if the request contains a rewrite
+ *
+ * @return bool
+ */
+ public function hasPendingRewrite(): bool
{
- return $this->hasRewrite;
+ return $this->hasPendingRewrite;
}
- public function setHasRewrite($value)
+ /**
+ * Defines if the current request contains a rewrite.
+ *
+ * @param bool $boolean
+ * @return Request
+ */
+ public function setHasPendingRewrite(bool $boolean): self
{
- $this->hasRewrite = $value;
+ $this->hasPendingRewrite = $boolean;
return $this;
}
- public function isRewrite($url)
- {
- return ($this->rewriteUrl === $url);
- }
-
public function __isset($name)
{
- return array_key_exists($name, $this->data);
+ return array_key_exists($name, $this->data) === true;
}
public function __set($name, $value = null)
@@ -347,7 +422,7 @@ class Request
public function __get($name)
{
- return isset($this->data[$name]) ? $this->data[$name] : null;
+ 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 f9f46f1..2e199f5 100644
--- a/src/Pecee/Http/Response.php
+++ b/src/Pecee/Http/Response.php
@@ -19,7 +19,7 @@ class Response
* @param int $code
* @return static
*/
- public function httpCode($code)
+ public function httpCode(int $code): self
{
http_response_code($code);
@@ -32,7 +32,7 @@ class Response
* @param string $url
* @param int $httpCode
*/
- public function redirect($url, $httpCode = null)
+ public function redirect(string $url, ?int $httpCode = null): void
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
@@ -42,7 +42,7 @@ class Response
exit(0);
}
- public function refresh()
+ public function refresh(): void
{
$this->redirect($this->request->getUrl()->getOriginalUrl());
}
@@ -52,7 +52,7 @@ class Response
* @param string $name
* @return static
*/
- public function auth($name = '')
+ public function auth(string $name = ''): self
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
@@ -62,23 +62,22 @@ class Response
return $this;
}
- public function cache($eTag, $lastModified = 2592000)
+ public function cache(string $eTag, int $lastModifiedTime = 2592000): self
{
$this->headers([
'Cache-Control: public',
- 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT',
- 'Etag: ' . $eTag,
+ sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)),
+ sprintf('Etag: %s', $eTag),
]);
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
- if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) {
+ if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModifiedTime)) {
$this->header('HTTP/1.1 304 Not Modified');
-
- exit();
+ exit(0);
}
return $this;
@@ -91,9 +90,9 @@ class Response
* @param int $dept JSON debt.
* @throws InvalidArgumentException
*/
- public function json($value, $options = null, $dept = 512)
+ public function json($value, ?int $options = null, int $dept = 512): void
{
- if (($value instanceof \JsonSerializable) === false && is_array($value) === false) {
+ if (($value instanceof \JsonSerializable) === false && \is_array($value) === false) {
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
}
@@ -107,7 +106,7 @@ class Response
* @param string $value
* @return static
*/
- public function header($value)
+ public function header(string $value): self
{
header($value);
@@ -119,7 +118,7 @@ class Response
* @param array $headers
* @return static
*/
- public function headers(array $headers)
+ public function headers(array $headers): self
{
foreach ($headers as $header) {
$this->header($header);
diff --git a/src/Pecee/Http/Security/CookieTokenProvider.php b/src/Pecee/Http/Security/CookieTokenProvider.php
index 209067f..b871b35 100644
--- a/src/Pecee/Http/Security/CookieTokenProvider.php
+++ b/src/Pecee/Http/Security/CookieTokenProvider.php
@@ -6,7 +6,7 @@ use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider
{
- const CSRF_KEY = 'CSRF-TOKEN';
+ public const CSRF_KEY = 'CSRF-TOKEN';
protected $token;
protected $cookieTimeoutMinutes = 120;
@@ -30,24 +30,13 @@ class CookieTokenProvider implements ITokenProvider
* @return string
* @throws SecurityException
*/
- public function generateToken()
+ public function generateToken(): string
{
- if (function_exists('random_bytes') === true) {
- try {
- return bin2hex(random_bytes(32));
- } catch(\Exception $e) {
- throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
- }
+ try {
+ return bin2hex(random_bytes(32));
+ } catch (\Exception $e) {
+ throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
-
- $isSourceStrong = false;
-
- $random = openssl_random_pseudo_bytes(32, $isSourceStrong);
- if ($isSourceStrong === false || $random === false) {
- throw new SecurityException('IV generation failed');
- }
-
- return $random;
}
/**
@@ -56,9 +45,9 @@ class CookieTokenProvider implements ITokenProvider
* @param string $token
* @return bool
*/
- public function validate($token)
+ public function validate(string $token): bool
{
- if ($token !== null && $this->getToken() !== null) {
+ if ($this->getToken() !== null) {
return hash_equals($token, $this->getToken());
}
@@ -71,10 +60,10 @@ class CookieTokenProvider implements ITokenProvider
*
* @param string $token
*/
- public function setToken($token)
+ public function setToken(string $token): void
{
$this->token = $token;
- setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/');
+ setcookie(static::CSRF_KEY, $token, (int)((time() + 60) * $this->cookieTimeoutMinutes), '/', ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
}
/**
@@ -82,17 +71,17 @@ class CookieTokenProvider implements ITokenProvider
* @param string|null $defaultValue
* @return string|null
*/
- public function getToken($defaultValue = null)
+ public function getToken(?string $defaultValue = null): ?string
{
$this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
- return ($this->token !== null) ? $this->token : $defaultValue;
+ return $this->token ?? $defaultValue;
}
/**
* Refresh existing token
*/
- public function refresh()
+ public function refresh(): void
{
if ($this->token !== null) {
$this->setToken($this->token);
@@ -103,7 +92,7 @@ class CookieTokenProvider implements ITokenProvider
* Returns whether the csrf token has been defined
* @return bool
*/
- public function hasToken()
+ public function hasToken(): bool
{
return isset($_COOKIE[static::CSRF_KEY]);
}
@@ -112,16 +101,16 @@ class CookieTokenProvider implements ITokenProvider
* Get timeout for cookie in minutes
* @return int
*/
- public function getCookieTimeoutMinutes()
+ public function getCookieTimeoutMinutes(): int
{
return $this->cookieTimeoutMinutes;
}
/**
* Set cookie timeout in minutes
- * @param $minutes
+ * @param int $minutes
*/
- public function setCookieTimeoutMinutes($minutes)
+ public function setCookieTimeoutMinutes(int $minutes): void
{
$this->cookieTimeoutMinutes = $minutes;
}
diff --git a/src/Pecee/Http/Security/Exceptions/SecurityException.php b/src/Pecee/Http/Security/Exceptions/SecurityException.php
index 6b63bfb..b7d2dc2 100644
--- a/src/Pecee/Http/Security/Exceptions/SecurityException.php
+++ b/src/Pecee/Http/Security/Exceptions/SecurityException.php
@@ -1,6 +1,8 @@
null,
- 'host' => null,
- 'port' => null,
- 'user' => null,
- 'pass' => null,
- 'path' => null,
- 'query' => null,
- 'fragment' => null,
- ];
+
+ private $scheme;
+ private $host;
+ private $port;
+ private $username;
+ private $password;
+ private $path;
+ private $params;
+ private $fragment;
/**
* Url constructor.
+ *
* @param string $url
* @throws MalformedUrlException
*/
- public function __construct($url)
+ public function __construct(?string $url)
{
$this->originalUrl = $url;
- $this->data = $this->parseUrl($url) + $this->data;
- if (isset($this->data['path']) === true && $this->data['path'] !== '/') {
- $this->data['path'] = rtrim($this->data['path'], '/') . '/';
+ if ($url !== null && $url !== '/') {
+ $data = $this->parseUrl($url);
+
+ $this->scheme = $data['scheme'] ?? null;
+ $this->host = $data['host'] ?? null;
+ $this->port = $data['port'] ?? null;
+ $this->username = $data['user'] ?? null;
+ $this->password = $data['pass'] ?? null;
+
+ if (isset($data['path']) === true) {
+ $this->setPath($data['path']);
+ }
+
+ $this->fragment = $data['fragment'] ?? null;
+
+ if (isset($data['query']) === true) {
+ $params = [];
+ parse_str($data['query'], $params);
+ $this->setParams($params);
+ }
}
-
}
/**
* Check if url is using a secure protocol like https
+ *
* @return bool
*/
- public function isSecure()
+ public function isSecure(): bool
{
return (strtolower($this->getScheme()) === 'https');
}
/**
* Checks if url is relative
+ *
* @return bool
*/
- public function isRelative()
+ public function isRelative(): bool
{
return ($this->getHost() === null);
}
/**
* Get url scheme
+ *
* @return string|null
*/
- public function getScheme()
+ public function getScheme(): ?string
{
- return $this->data['scheme'];
+ return $this->scheme;
+ }
+
+ /**
+ * Set the scheme of the url
+ *
+ * @param string $scheme
+ * @return static
+ */
+ public function setScheme(string $scheme): self
+ {
+ $this->scheme = $scheme;
+
+ return $this;
}
/**
* Get url host
+ *
* @return string|null
*/
- public function getHost()
+ public function getHost(): ?string
{
- return $this->data['host'];
+ return $this->host;
+ }
+
+ /**
+ * Set the host of the url
+ *
+ * @param string $host
+ * @return static
+ */
+ public function setHost(string $host): self
+ {
+ $this->host = $host;
+
+ return $this;
}
/**
* Get url port
+ *
* @return int|null
*/
- public function getPort()
+ public function getPort(): ?int
{
- return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
+ return ($this->port !== null) ? (int)$this->port : null;
+ }
+
+ /**
+ * Set the port of the url
+ *
+ * @param int $port
+ * @return static
+ */
+ public function setPort(int $port): self
+ {
+ $this->port = $port;
+
+ return $this;
}
/**
* Parse username from url
+ *
* @return string|null
*/
- public function getUserName()
+ public function getUsername(): ?string
{
- return $this->data['user'];
+ return $this->username;
+ }
+
+ /**
+ * Set the username of the url
+ *
+ * @param string $username
+ * @return static
+ */
+ public function setUsername(string $username): self
+ {
+ $this->username = $username;
+
+ return $this;
}
/**
* Parse password from url
* @return string|null
*/
- public function getPassword()
+ public function getPassword(): ?string
{
- return $this->data['pass'];
+ return $this->password;
+ }
+
+ /**
+ * Set the url password
+ *
+ * @param string $password
+ * @return static
+ */
+ public function setPassword(string $password): self
+ {
+ $this->password = $password;
+
+ return $this;
}
/**
* Get path from url
* @return string
*/
- public function getPath()
+ public function getPath(): ?string
{
- return $this->data['path'];
+ return $this->path ?? '/';
}
/**
- * Get querystring from url
- * @return string|null
+ * Set the url path
+ *
+ * @param string $path
+ * @return static
*/
- public function getQueryString()
+ public function setPath(string $path): self
{
- return $this->data['query'];
+ $this->path = rtrim($path, '/') . '/';
+
+ return $this;
+ }
+
+ /**
+ * Get query-string from url
+ *
+ * @return array
+ */
+ public function getParams(): array
+ {
+ return $this->params;
+ }
+
+ /**
+ * Merge parameters array
+ *
+ * @param array $params
+ * @return static
+ */
+ public function mergeParams(array $params): self
+ {
+ return $this->setParams(array_merge($this->getParams(), $params));
+ }
+
+ /**
+ * Set the url params
+ *
+ * @param array $params
+ * @return static
+ */
+ public function setParams(array $params): self
+ {
+ $this->params = $params;
+
+ return $this;
+ }
+
+ /**
+ * Get query-string params as string
+ *
+ * @return string
+ */
+ public function getQueryString(): string
+ {
+ return static::arrayToParams($this->getParams());
}
/**
* Get fragment from url (everything after #)
+ *
* @return string|null
*/
- public function getFragment()
+ public function getFragment(): ?string
{
- return $this->data['fragment'];
+ return $this->fragment;
+ }
+
+ /**
+ * Set url fragment
+ *
+ * @param string $fragment
+ * @return static
+ */
+ public function setFragment(string $fragment): self
+ {
+ $this->fragment = $fragment;
+
+ return $this;
}
/**
* @return string
*/
- public function getOriginalUrl()
+ public function getOriginalUrl(): string
{
return $this->originalUrl;
}
+ /**
+ * Get position of value.
+ * Returns -1 on failure.
+ *
+ * @param string $value
+ * @return int
+ */
+ public function indexOf(string $value): int
+ {
+ $index = stripos($this->getOriginalUrl(), $value);
+
+ return ($index === false) ? -1 : $index;
+ }
+
+ /**
+ * Check if url contains value.
+ *
+ * @param string $value
+ * @return bool
+ */
+ public function contains(string $value): bool
+ {
+ return (stripos($this->getOriginalUrl(), $value) !== false);
+ }
+
+ /**
+ * Check if url contains parameter/query string.
+ *
+ * @param string $name
+ * @return bool
+ */
+ public function hasParam(string $name): bool
+ {
+ return array_key_exists($name, $this->getParams());
+ }
+
+ /**
+ * Removes multiple parameters from the query-string
+ *
+ * @param array ...$names
+ * @return static
+ */
+ public function removeParams(...$names): self
+ {
+ $params = array_diff_key($this->getParams(), array_flip($names));
+ $this->setParams($params);
+
+ return $this;
+ }
+
+ /**
+ * Removes parameter from the query-string
+ *
+ * @param string $name
+ * @return static
+ */
+ public function removeParam(string $name): self
+ {
+ $params = $this->getParams();
+ unset($params[$name]);
+ $this->setParams($params);
+
+ return $this;
+ }
+
+ /**
+ * Get parameter by name.
+ * Returns parameter value or default value.
+ *
+ * @param string $name
+ * @param string|null $defaultValue
+ * @return string|null
+ */
+ public function getParam(string $name, ?string $defaultValue = null): ?string
+ {
+ return isset($this->getParams()[$name]) ?? $defaultValue;
+ }
+
/**
* UTF-8 aware parse_url() replacement.
* @param string $url
* @param int $component
- * @throws MalformedUrlException
* @return array
+ * @throws MalformedUrlException
*/
- public function parseUrl($url, $component = -1)
+ public function parseUrl(string $url, int $component = -1): array
{
$encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u',
@@ -152,24 +379,83 @@ class Url
$parts = parse_url($encodedUrl, $component);
if ($parts === false) {
- throw new MalformedUrlException('Malformed URL: ' . $url);
+ throw new MalformedUrlException(sprintf('Failed to parse url: "%s"', $url));
}
return array_map('urldecode', $parts);
}
/**
- * Returns data array with information about the url
- * @return array
+ * Convert array to query-string params
+ *
+ * @param array $getParams
+ * @param bool $includeEmpty
+ * @return string
*/
- public function getData()
+ public static function arrayToParams(array $getParams = [], bool $includeEmpty = true): string
{
- return $this->data;
+ if (\count($getParams) !== 0) {
+
+ if ($includeEmpty === false) {
+ $getParams = array_filter($getParams, function ($item) {
+ return (trim($item) !== '');
+ });
+ }
+
+ return http_build_query($getParams);
+ }
+
+ return '';
}
- public function __toString()
+ /**
+ * Returns the relative url
+ *
+ * @return string
+ */
+ public function getRelativeUrl(): string
{
- return $this->getOriginalUrl();
+ $params = $this->getQueryString();
+
+ $path = $this->path ?? '';
+ $query = $params !== '' ? '?' . $params : '';
+ $fragment = $this->fragment !== null ? '#' . $this->fragment : '';
+
+ return $path . $query . $fragment;
+ }
+
+ /**
+ * Returns the absolute url
+ *
+ * @return string
+ */
+ public function getAbsoluteUrl(): string
+ {
+ $scheme = $this->scheme !== null ? $this->scheme . '://' : '';
+ $host = $this->host ?? '';
+ $port = $this->port !== null ? ':' . $this->port : '';
+ $user = $this->username ?? '';
+ $pass = $this->password !== null ? ':' . $this->password : '';
+ $pass = ($user || $pass) ? $pass . '@' : '';
+
+ return $scheme . $user . $pass . $host . $port . $this->getRelativeUrl();
+ }
+
+ /**
+ * Specify data which should be serialized to JSON
+ * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return mixed data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
+ */
+ public function jsonSerialize(): string
+ {
+ return $this->getRelativeUrl();
+ }
+
+ public function __toString(): string
+ {
+ return $this->getRelativeUrl();
}
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php b/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php
new file mode 100644
index 0000000..caea1a5
--- /dev/null
+++ b/src/Pecee/SimpleRouter/ClassLoader/ClassLoader.php
@@ -0,0 +1,118 @@
+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());
+ }
+ }
+ }
+
+ return new $class();
+ }
+
+ /**
+ * Load closure
+ *
+ * @param \Closure $closure
+ * @param array $parameters
+ * @return mixed
+ * @throws NotFoundHttpException
+ */
+ public function loadClosure(\Closure $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
new file mode 100644
index 0000000..d978ac1
--- /dev/null
+++ b/src/Pecee/SimpleRouter/ClassLoader/IClassLoader.php
@@ -0,0 +1,12 @@
+eventName = $eventName;
+ $this->router = $router;
+ $this->arguments = $arguments;
+ }
+
+ /**
+ * Get event name
+ *
+ * @return string
+ */
+ public function getEventName(): string
+ {
+ return $this->eventName;
+ }
+
+ /**
+ * Set the event name
+ *
+ * @param string $name
+ */
+ public function setEventName(string $name): void
+ {
+ $this->eventName = $name;
+ }
+
+ /**
+ * Get the router instance
+ *
+ * @return Router
+ */
+ public function getRouter(): Router
+ {
+ return $this->router;
+ }
+
+ /**
+ * Get the request instance
+ *
+ * @return Request
+ */
+ public function getRequest(): Request
+ {
+ return $this->getRouter()->getRequest();
+ }
+
+ /**
+ * @param string $name
+ * @return mixed
+ */
+ public function __get($name)
+ {
+ return $this->arguments[$name] ?? null;
+ }
+
+ /**
+ * @param string $name
+ * @return bool
+ */
+ public function __isset($name)
+ {
+ return array_key_exists($name, $this->arguments);
+ }
+
+ /**
+ * @param string $name
+ * @param mixed $value
+ * @throws \InvalidArgumentException
+ */
+ public function __set($name, $value)
+ {
+ throw new \InvalidArgumentException('Not supported');
+ }
+
+ /**
+ * Get arguments
+ *
+ * @return array
+ */
+ public function getArguments(): array
+ {
+ return $this->arguments;
+ }
+
+}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Event/IEventArgument.php b/src/Pecee/SimpleRouter/Event/IEventArgument.php
new file mode 100644
index 0000000..a8a6d7e
--- /dev/null
+++ b/src/Pecee/SimpleRouter/Event/IEventArgument.php
@@ -0,0 +1,46 @@
+callback,
+ \call_user_func($this->callback,
$request,
$error
);
diff --git a/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php b/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php
new file mode 100644
index 0000000..690b275
--- /dev/null
+++ b/src/Pecee/SimpleRouter/Handlers/DebugEventHandler.php
@@ -0,0 +1,62 @@
+callback = function (EventArgument $argument) {
+ // todo: log in database
+ };
+ }
+
+ /**
+ * Get events.
+ *
+ * @param string|null $name Filter events by name.
+ * @return array
+ */
+ public function getEvents(?string $name): array
+ {
+ return [
+ $name => [
+ $this->callback,
+ ],
+ ];
+ }
+
+ /**
+ * Fires any events registered with given event-name
+ *
+ * @param Router $router Router instance
+ * @param string $name Event name
+ * @param array $eventArgs Event arguments
+ */
+ public function fireEvents(Router $router, string $name, array $eventArgs = []): void
+ {
+ $callback = $this->callback;
+ $callback(new EventArgument($router, $eventArgs));
+ }
+
+ /**
+ * Set debug callback
+ *
+ * @param \Closure $event
+ */
+ public function setCallback(\Closure $event): void
+ {
+ $this->callback = $event;
+ }
+
+}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Handlers/EventHandler.php b/src/Pecee/SimpleRouter/Handlers/EventHandler.php
new file mode 100644
index 0000000..9ac42ec
--- /dev/null
+++ b/src/Pecee/SimpleRouter/Handlers/EventHandler.php
@@ -0,0 +1,184 @@
+registeredEvents[$name]) === true) {
+ $this->registeredEvents[$name][] = $callback;
+ } else {
+ $this->registeredEvents[$name] = [$callback];
+ }
+
+ return $this;
+ }
+
+ /**
+ * Get events.
+ *
+ * @param string|null $name Filter events by name.
+ * @param array ...$names Add multiple names...
+ * @return array
+ */
+ public function getEvents(?string $name, ...$names): array
+ {
+ if ($name === null) {
+ return $this->registeredEvents;
+ }
+
+ $names[] = $name;
+ $events = [];
+
+ foreach ($names as $eventName) {
+ if (isset($this->registeredEvents[$eventName]) === true) {
+ $events += $this->registeredEvents[$eventName];
+ }
+ }
+
+ return $events;
+ }
+
+ /**
+ * Fires any events registered with given event-name
+ *
+ * @param Router $router Router instance
+ * @param string $name Event name
+ * @param array $eventArgs Event arguments
+ */
+ public function fireEvents(Router $router, string $name, array $eventArgs = []): void
+ {
+ $events = $this->getEvents(static::EVENT_ALL, $name);
+
+ /* @var $event \Closure */
+ foreach ($events as $event) {
+ $event(new EventArgument($name, $router, $eventArgs));
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/Handlers/IEventHandler.php b/src/Pecee/SimpleRouter/Handlers/IEventHandler.php
new file mode 100644
index 0000000..bf4e49a
--- /dev/null
+++ b/src/Pecee/SimpleRouter/Handlers/IEventHandler.php
@@ -0,0 +1,27 @@
+debug('Loading middlewares');
+
foreach ($this->getMiddlewares() as $middleware) {
- if (is_object($middleware) === false) {
- $middleware = $this->loadClass($middleware);
+ if (\is_object($middleware) === false) {
+ $middleware = $router->getClassLoader()->loadClass($middleware);
}
if (($middleware instanceof IMiddleware) === false) {
throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
}
+ $className = \get_class($middleware);
+
+ $router->debug('Loading middleware "%s"', $className);
$middleware->handle($request);
+ $router->debug('Finished loading middleware "%s"', $className);
}
+
+ $router->debug('Finished loading middlewares');
}
- public function matchRegex(Request $request, $url)
+ public function matchRegex(Request $request, $url): ?bool
{
/* Match on custom defined regular expression */
@@ -59,7 +69,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $url
* @return static
*/
- public function setUrl($url)
+ public function setUrl(string $url): ILoadableRoute
{
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
@@ -75,7 +85,18 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return $this;
}
- public function getUrl()
+ /**
+ * Prepend url
+ *
+ * @param string $url
+ * @return ILoadableRoute
+ */
+ public function prependUrl(string $url): ILoadableRoute
+ {
+ return $this->setUrl(rtrim($url, '/') . $this->url);
+ }
+
+ public function getUrl(): string
{
return $this->url;
}
@@ -89,13 +110,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|null $name
* @return string
*/
- public function findUrl($method = null, $parameters = null, $name = null)
+ public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string
{
$url = $this->getUrl();
$group = $this->getGroup();
- if ($group !== null && count($group->getDomains()) !== 0) {
+ if ($group !== null && \count($group->getDomains()) !== 0) {
$url = '//' . $group->getDomains()[0] . $url;
}
@@ -114,7 +135,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
foreach (array_keys($params) as $param) {
- if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
+ if ($parameters === '' || (\is_array($parameters) === true && \count($parameters) === 0)) {
$value = '';
} else {
$p = (array)$parameters;
@@ -144,7 +165,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*
* @return string
*/
- public function getName()
+ public function getName(): ?string
{
return $this->name;
}
@@ -155,9 +176,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $name
* @return bool
*/
- public function hasName($name)
+ public function hasName(string $name): bool
{
- return (strtolower($this->name) === strtolower($name));
+ return strtolower($this->name) === strtolower($name);
}
/**
@@ -166,7 +187,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $regex
* @return static
*/
- public function setMatch($regex)
+ public function setMatch($regex): ILoadableRoute
{
$this->regex = $regex;
@@ -178,7 +199,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*
* @return string
*/
- public function getMatch()
+ public function getMatch(): string
{
return $this->regex;
}
@@ -191,7 +212,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|array $name
* @return static
*/
- public function name($name)
+ public function name($name): ILoadableRoute
{
return $this->setName($name);
}
@@ -200,9 +221,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
- * @return static $this
+ * @return static
*/
- public function setName($name)
+ public function setName(string $name): ILoadableRoute
{
$this->name = $name;
@@ -216,7 +237,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, $merge = false)
+ public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['as']) === true) {
@@ -230,7 +251,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
}
if (isset($values['prefix']) === true) {
- $this->setUrl($values['prefix'] . $this->getUrl());
+ $this->prependUrl($values['prefix']);
}
parent::setSettings($values, $merge);
diff --git a/src/Pecee/SimpleRouter/Route/Route.php b/src/Pecee/SimpleRouter/Route/Route.php
index 8ebd681..c71686c 100644
--- a/src/Pecee/SimpleRouter/Route/Route.php
+++ b/src/Pecee/SimpleRouter/Route/Route.php
@@ -5,18 +5,19 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
+use Pecee\SimpleRouter\Router;
abstract class Route implements IRoute
{
- const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
- const PARAMETERS_DEFAULT_REGEX = '[\w]+';
+ protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
+ protected const PARAMETERS_DEFAULT_REGEX = '[\w]+';
- const REQUEST_TYPE_GET = 'get';
- const REQUEST_TYPE_POST = 'post';
- const REQUEST_TYPE_PUT = 'put';
- const REQUEST_TYPE_PATCH = 'patch';
- const REQUEST_TYPE_OPTIONS = 'options';
- const REQUEST_TYPE_DELETE = 'delete';
+ 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 static $requestTypes = [
self::REQUEST_TYPE_GET,
@@ -56,40 +57,29 @@ abstract class Route implements IRoute
protected $originalParameters = [];
protected $middlewares = [];
- /**
- * Load class by name
- * @param string $name
- * @return mixed
- * @throws NotFoundHttpException
- */
- protected function loadClass($name)
- {
- if (class_exists($name) === false) {
- throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $name), 404);
- }
-
- return new $name();
- }
-
/**
* Render route
*
* @param Request $request
- * @return string|mixed
+ * @param Router $router
+ * @return string|null
* @throws NotFoundHttpException
*/
- public function renderRoute(Request $request)
+ public function renderRoute(Request $request, Router $router): ?string
{
+ $router->debug('Starting rendering route "%s"', \get_class($this));
+
$callback = $this->getCallback();
if ($callback === null) {
return null;
}
+ $router->debug('Parsing parameters');
$parameters = $this->getParameters();
+ $router->debug('Finished parsing parameters');
/* Filter parameters with null-value */
-
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) {
return ($var !== null);
@@ -97,9 +87,12 @@ abstract class Route implements IRoute
}
/* Render callback function */
- if (is_callable($callback) === true) {
+ if (\is_callable($callback) === true) {
+ $router->debug('Executing callback');
+
/* When the callback is a function */
- return call_user_func_array($callback, $parameters);
+
+ return $router->getClassLoader()->loadClosure($callback, $parameters);
}
/* When the callback is a class + method */
@@ -109,14 +102,18 @@ abstract class Route implements IRoute
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
- $class = $this->loadClass($className);
+ $router->debug('Loading class %s', $className);
+ $class = $router->getClassLoader()->loadClass($className);
+
$method = $controller[1];
if (method_exists($class, $method) === false) {
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
}
- return call_user_func_array([$class, $method], $parameters);
+ $router->debug('Executing callback');
+
+ return \call_user_func_array([$class, $method], $parameters);
}
protected function parseParameters($route, $url, $parameterRegex = null)
@@ -125,7 +122,7 @@ abstract class Route implements IRoute
$parameters = [];
- // Ensures that hostnames/domains will work with parameters
+ // Ensures that host names/domains will work with parameters
$url = '/' . ltrim($url, '/');
if ((bool)preg_match_all('/' . $regex . '/u', $route, $parameters) === false) {
@@ -138,7 +135,7 @@ abstract class Route implements IRoute
$regex = '';
- if ($key < count($parameters[1])) {
+ if ($key < \count($parameters[1])) {
$name = $parameters[1][$key];
@@ -151,7 +148,7 @@ abstract class Route implements IRoute
if ($parameterRegex !== null) {
$regex = $parameterRegex;
} else {
- $regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex;
+ $regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
}
}
@@ -189,22 +186,22 @@ abstract class Route implements IRoute
*
* @return string
*/
- public function getIdentifier()
+ public function getIdentifier(): string
{
- if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
+ if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
return $this->callback;
}
- return 'function_' . md5($this->callback);
+ return 'function:' . md5($this->callback);
}
/**
* Set allowed request methods
*
* @param array $methods
- * @return static $this
+ * @return static
*/
- public function setRequestMethods(array $methods)
+ public function setRequestMethods(array $methods): IRoute
{
$this->requestMethods = $methods;
@@ -216,7 +213,7 @@ abstract class Route implements IRoute
*
* @return array
*/
- public function getRequestMethods()
+ public function getRequestMethods(): array
{
return $this->requestMethods;
}
@@ -224,7 +221,7 @@ abstract class Route implements IRoute
/**
* @return IRoute|null
*/
- public function getParent()
+ public function getParent(): ?IRoute
{
return $this->parent;
}
@@ -234,7 +231,7 @@ abstract class Route implements IRoute
*
* @return IGroupRoute|null
*/
- public function getGroup()
+ public function getGroup(): ?IGroupRoute
{
return $this->group;
}
@@ -243,9 +240,9 @@ abstract class Route implements IRoute
* Set group
*
* @param IGroupRoute $group
- * @return static $this
+ * @return static
*/
- public function setGroup(IGroupRoute $group)
+ public function setGroup(IGroupRoute $group): IRoute
{
$this->group = $group;
@@ -259,9 +256,9 @@ abstract class Route implements IRoute
* Set parent route
*
* @param IRoute $parent
- * @return static $this
+ * @return static
*/
- public function setParent(IRoute $parent)
+ public function setParent(IRoute $parent): IRoute
{
$this->parent = $parent;
@@ -274,7 +271,7 @@ abstract class Route implements IRoute
* @param string $callback
* @return static
*/
- public function setCallback($callback)
+ public function setCallback($callback): IRoute
{
$this->callback = $callback;
@@ -282,16 +279,16 @@ abstract class Route implements IRoute
}
/**
- * @return string
+ * @return string|callable
*/
public function getCallback()
{
return $this->callback;
}
- public function getMethod()
+ public function getMethod(): ?string
{
- if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
+ if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[1];
@@ -300,9 +297,9 @@ abstract class Route implements IRoute
return null;
}
- public function getClass()
+ public function getClass(): ?string
{
- if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
+ if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[0];
@@ -311,14 +308,14 @@ abstract class Route implements IRoute
return null;
}
- public function setMethod($method)
+ public function setMethod(string $method): IRoute
{
$this->callback = sprintf('%s@%s', $this->getClass(), $method);
return $this;
}
- public function setClass($class)
+ public function setClass(string $class): IRoute
{
$this->callback = sprintf('%s@%s', $class, $this->getMethod());
@@ -327,9 +324,9 @@ abstract class Route implements IRoute
/**
* @param string $namespace
- * @return static $this
+ * @return static
*/
- public function setNamespace($namespace)
+ public function setNamespace(string $namespace): IRoute
{
$this->namespace = $namespace;
@@ -338,26 +335,26 @@ abstract class Route implements IRoute
/**
* @param string $namespace
- * @return static $this
+ * @return static
*/
- public function setDefaultNamespace($namespace)
+ public function setDefaultNamespace($namespace): IRoute
{
$this->defaultNamespace = $namespace;
return $this;
}
- public function getDefaultNamespace()
+ public function getDefaultNamespace(): ?string
{
return $this->defaultNamespace;
}
/**
- * @return string
+ * @return string|null
*/
- public function getNamespace()
+ public function getNamespace(): ?string
{
- return ($this->namespace === null) ? $this->defaultNamespace : $this->namespace;
+ return $this->namespace ?? $this->defaultNamespace;
}
/**
@@ -365,7 +362,7 @@ abstract class Route implements IRoute
*
* @return array
*/
- public function toArray()
+ public function toArray(): array
{
$values = [];
@@ -373,15 +370,15 @@ abstract class Route implements IRoute
$values['namespace'] = $this->namespace;
}
- if (count($this->requestMethods) !== 0) {
+ if (\count($this->requestMethods) !== 0) {
$values['method'] = $this->requestMethods;
}
- if (count($this->where) !== 0) {
+ if (\count($this->where) !== 0) {
$values['where'] = $this->where;
}
- if (count($this->middlewares) !== 0) {
+ if (\count($this->middlewares) !== 0) {
$values['middleware'] = $this->middlewares;
}
@@ -397,9 +394,9 @@ abstract class Route implements IRoute
*
* @param array $values
* @param bool $merge
- * @return static $this
+ * @return static
*/
- public function setSettings(array $values, $merge = false)
+ public function setSettings(array $values, bool $merge = false): IRoute
{
if ($this->namespace === null && isset($values['namespace']) === true) {
$this->setNamespace($values['namespace']);
@@ -434,7 +431,7 @@ abstract class Route implements IRoute
*
* @return array
*/
- public function getWhere()
+ public function getWhere(): array
{
return $this->where;
}
@@ -445,7 +442,7 @@ abstract class Route implements IRoute
* @param array $options
* @return static
*/
- public function setWhere(array $options)
+ public function setWhere(array $options): IRoute
{
$this->where = $options;
@@ -470,12 +467,12 @@ abstract class Route implements IRoute
*
* @return array
*/
- public function getParameters()
+ public function getParameters(): array
{
/* Sort the parameters after the user-defined param order, if any */
$parameters = [];
- if (count($this->originalParameters) !== 0) {
+ if (\count($this->originalParameters) !== 0) {
$parameters = $this->originalParameters;
}
@@ -486,15 +483,15 @@ abstract class Route implements IRoute
* Get parameters
*
* @param array $parameters
- * @return static $this
+ * @return static
*/
- public function setParameters(array $parameters)
+ public function setParameters(array $parameters): IRoute
{
/*
* If this is the first time setting parameters we store them so we
* later can organize the array, in case somebody tried to sort the array.
*/
- if (count($parameters) !== 0 && count($this->originalParameters) === 0) {
+ if (\count($parameters) !== 0 && \count($this->originalParameters) === 0) {
$this->originalParameters = $parameters;
}
@@ -523,7 +520,7 @@ abstract class Route implements IRoute
* @param IMiddleware|string $middleware
* @return static
*/
- public function addMiddleware($middleware)
+ public function addMiddleware($middleware): IRoute
{
$this->middlewares[] = $middleware;
@@ -534,9 +531,9 @@ abstract class Route implements IRoute
* Set middlewares array
*
* @param array $middlewares
- * @return $this
+ * @return static
*/
- public function setMiddlewares(array $middlewares)
+ public function setMiddlewares(array $middlewares): IRoute
{
$this->middlewares = $middlewares;
@@ -546,7 +543,7 @@ abstract class Route implements IRoute
/**
* @return array
*/
- public function getMiddlewares()
+ public function getMiddlewares(): array
{
return $this->middlewares;
}
@@ -556,7 +553,7 @@ abstract class Route implements IRoute
* This is used when no custom parameter regex is found.
*
* @param string $regex
- * @return static $this
+ * @return static
*/
public function setDefaultParameterRegex($regex)
{
@@ -570,7 +567,7 @@ abstract class Route implements IRoute
*
* @return string
*/
- public function getDefaultParameterRegex()
+ public function getDefaultParameterRegex(): string
{
return $this->defaultParameterRegex;
}
diff --git a/src/Pecee/SimpleRouter/Route/RouteController.php b/src/Pecee/SimpleRouter/Route/RouteController.php
index 25cfe4f..e090652 100644
--- a/src/Pecee/SimpleRouter/Route/RouteController.php
+++ b/src/Pecee/SimpleRouter/Route/RouteController.php
@@ -24,7 +24,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $name
* @return bool
*/
- public function hasName($name)
+ public function hasName(string $name): bool
{
if ($this->name === null) {
return false;
@@ -35,7 +35,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.'));
- if (in_array($method, $this->names, false) === true && strtolower($this->name) === strtolower($newName)) {
+ if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
return true;
}
}
@@ -49,7 +49,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string|null $name
* @return string
*/
- public function findUrl($method = null, $parameters = null, $name = null)
+ public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string
{
if (strpos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
@@ -67,7 +67,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
foreach (static::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) {
- $method = (string)substr($method, strlen($requestType));
+ $method = (string)substr($method, \strlen($requestType));
break;
}
}
@@ -77,7 +77,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$group = $this->getGroup();
- if ($group !== null && count($group->getDomains()) !== 0) {
+ if ($group !== null && \count($group->getDomains()) !== 0) {
$url .= '//' . $group->getDomains()[0];
}
@@ -86,9 +86,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
return '/' . trim($url, '/') . '/';
}
- public function matchRoute($url, Request $request)
+ public function matchRoute($url, Request $request): bool
{
- if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
+ if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
@@ -102,12 +102,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl);
- if (count($path) !== 0) {
+ if (\count($path) !== 0) {
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method);
- $this->parameters = array_slice($path, 1);
+ $this->parameters = \array_slice($path, 1);
// Set callback
$this->setCallback($this->controller . '@' . $this->method);
@@ -123,7 +123,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
*
* @return string
*/
- public function getController()
+ public function getController(): string
{
return $this->controller;
}
@@ -134,7 +134,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $controller
* @return static
*/
- public function setController($controller)
+ public function setController(string $controller): IControllerRoute
{
$this->controller = $controller;
@@ -144,9 +144,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
/**
* Return active method
*
- * @return string
+ * @return string|null
*/
- public function getMethod()
+ public function getMethod(): ?string
{
return $this->method;
}
@@ -157,7 +157,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $method
* @return static
*/
- public function setMethod($method)
+ public function setMethod(string $method): IRoute
{
$this->method = $method;
@@ -171,7 +171,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, $merge = false)
+ public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['names']) === true) {
$this->names = $values['names'];
diff --git a/src/Pecee/SimpleRouter/Route/RouteGroup.php b/src/Pecee/SimpleRouter/Route/RouteGroup.php
index 4e3bde1..4e72215 100644
--- a/src/Pecee/SimpleRouter/Route/RouteGroup.php
+++ b/src/Pecee/SimpleRouter/Route/RouteGroup.php
@@ -2,8 +2,8 @@
namespace Pecee\SimpleRouter\Route;
-use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Request;
+use Pecee\SimpleRouter\Handlers\IExceptionHandler;
class RouteGroup extends Route implements IGroupRoute
{
@@ -18,9 +18,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @return bool
*/
- public function matchDomain(Request $request)
+ public function matchDomain(Request $request): bool
{
- if ($this->domains === null || count($this->domains) === 0) {
+ if ($this->domains === null || \count($this->domains) === 0) {
return true;
}
@@ -28,7 +28,7 @@ class RouteGroup extends Route implements IGroupRoute
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
- if ($parameters !== null && count($parameters) !== 0) {
+ if ($parameters !== null && \count($parameters) !== 0) {
$this->parameters = $parameters;
@@ -46,9 +46,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @return bool
*/
- public function matchRoute($url, Request $request)
+ public function matchRoute($url, Request $request): bool
{
- if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
+ if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
@@ -64,9 +64,9 @@ class RouteGroup extends Route implements IGroupRoute
* Add exception handler
*
* @param IExceptionHandler|string $handler
- * @return static $this
+ * @return static
*/
- public function addExceptionHandler($handler)
+ public function addExceptionHandler($handler): IGroupRoute
{
$this->exceptionHandlers[] = $handler;
@@ -77,9 +77,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set exception-handlers for group
*
* @param array $handlers
- * @return static $this
+ * @return static
*/
- public function setExceptionHandlers(array $handlers)
+ public function setExceptionHandlers(array $handlers): IGroupRoute
{
$this->exceptionHandlers = $handlers;
@@ -91,7 +91,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
- public function getExceptionHandlers()
+ public function getExceptionHandlers(): array
{
return $this->exceptionHandlers;
}
@@ -101,7 +101,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
- public function getDomains()
+ public function getDomains(): array
{
return $this->domains;
}
@@ -110,9 +110,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set allowed domains for group.
*
* @param array $domains
- * @return $this
+ * @return static
*/
- public function setDomains(array $domains)
+ public function setDomains(array $domains): IGroupRoute
{
$this->domains = $domains;
@@ -123,7 +123,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix
* @return static
*/
- public function setPrefix($prefix)
+ public function setPrefix($prefix): IGroupRoute
{
$this->prefix = '/' . trim($prefix, '/');
@@ -133,9 +133,9 @@ class RouteGroup extends Route implements IGroupRoute
/**
* Set prefix that child-routes will inherit.
*
- * @return string
+ * @return string|null
*/
- public function getPrefix()
+ public function getPrefix(): ?string
{
return $this->prefix;
}
@@ -147,7 +147,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, $merge = false)
+ public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['prefix']) === true) {
@@ -183,7 +183,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
- public function toArray()
+ public function toArray(): array
{
$values = [];
@@ -195,7 +195,7 @@ class RouteGroup extends Route implements IGroupRoute
$values['as'] = $this->name;
}
- if (count($this->parameters) !== 0) {
+ if (\count($this->parameters) !== 0) {
$values['parameters'] = $this->parameters;
}
diff --git a/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php b/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php
index 51b71e0..956c248 100644
--- a/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php
+++ b/src/Pecee/SimpleRouter/Route/RoutePartialGroup.php
@@ -6,7 +6,14 @@ use Pecee\Http\Request;
class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
{
- protected $urlRegex = '/^%s\/?/u';
+
+ /**
+ * RoutePartialGroup constructor.
+ */
+ public function __construct()
+ {
+ $this->urlRegex = '/^%s\/?/u';
+ }
/**
* Method called to check if route matches
@@ -15,12 +22,12 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
* @param Request $request
* @return bool
*/
- public function matchRoute($url, Request $request)
+ public function matchRoute($url, Request $request): bool
{
- if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
+ if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
-
+
if ($this->prefix !== null) {
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url);
diff --git a/src/Pecee/SimpleRouter/Route/RouteResource.php b/src/Pecee/SimpleRouter/Route/RouteResource.php
index 108e51a..2096831 100644
--- a/src/Pecee/SimpleRouter/Route/RouteResource.php
+++ b/src/Pecee/SimpleRouter/Route/RouteResource.php
@@ -42,7 +42,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $name
* @return bool
*/
- public function hasName($name)
+ public function hasName(string $name): bool
{
if ($this->name === null) {
return false;
@@ -60,7 +60,13 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return (strtolower($this->name) === strtolower($name));
}
- public function findUrl($method = null, $parameters = null, $name = null)
+ /**
+ * @param string|null $method
+ * @param array|string|null $parameters
+ * @param string|null $name
+ * @return string
+ */
+ public function findUrl(?string $method = null, $parameters = null, ?string $name = null): string
{
$url = array_search($name, $this->names, false);
if ($url !== false) {
@@ -77,9 +83,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return true;
}
- public function matchRoute($url, Request $request)
+ public function matchRoute($url, Request $request): bool
{
- if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
+ if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
@@ -114,7 +120,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
}
// Update
- if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
+ if ($id !== null && \in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], true) === true) {
return $this->call($this->methodNames['update']);
}
@@ -145,7 +151,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* @return string
*/
- public function getController()
+ public function getController(): string
{
return $this->controller;
}
@@ -154,14 +160,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $controller
* @return static
*/
- public function setController($controller)
+ public function setController(string $controller): IControllerRoute
{
$this->controller = $controller;
return $this;
}
- public function setName($name)
+ public function setName(string $name): ILoadableRoute
{
$this->name = $name;
@@ -194,9 +200,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* Get method names
*
- * @return array $this
+ * @return array
*/
- public function getMethodNames()
+ public function getMethodNames(): array
{
return $this->methodNames;
}
@@ -208,7 +214,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param bool $merge
* @return static
*/
- public function setSettings(array $values, $merge = false)
+ public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['names']) === true) {
$this->names = $values['names'];
diff --git a/src/Pecee/SimpleRouter/Route/RouteUrl.php b/src/Pecee/SimpleRouter/Route/RouteUrl.php
index 19eb137..cdfcb60 100644
--- a/src/Pecee/SimpleRouter/Route/RouteUrl.php
+++ b/src/Pecee/SimpleRouter/Route/RouteUrl.php
@@ -12,9 +12,9 @@ class RouteUrl extends LoadableRoute
$this->setCallback($callback);
}
- public function matchRoute($url, Request $request)
+ public function matchRoute($url, Request $request): bool
{
- if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
+ 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 a34e350..50acc48 100644
--- a/src/Pecee/SimpleRouter/Router.php
+++ b/src/Pecee/SimpleRouter/Router.php
@@ -3,11 +3,17 @@
namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException;
-use Pecee\Handlers\IExceptionHandler;
+use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
+use Pecee\Http\Url;
+use Pecee\SimpleRouter\ClassLoader\ClassLoader;
+use Pecee\SimpleRouter\ClassLoader\IClassLoader;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
+use Pecee\SimpleRouter\Handlers\EventHandler;
+use Pecee\SimpleRouter\Handlers\IEventHandler;
+use Pecee\SimpleRouter\Handlers\IExceptionHandler;
use Pecee\SimpleRouter\Route\IControllerRoute;
use Pecee\SimpleRouter\Route\IGroupRoute;
use Pecee\SimpleRouter\Route\ILoadableRoute;
@@ -27,32 +33,32 @@ class Router
* Defines if a route is currently being processed.
* @var bool
*/
- protected $processingRoute;
+ protected $isProcessingRoute;
/**
* All added routes
* @var array
*/
- protected $routes;
+ protected $routes = [];
/**
* List of processed routes
* @var array
*/
- protected $processedRoutes;
+ protected $processedRoutes = [];
/**
* Stack of routes used to keep track of sub-routes added
* when a route is being processed.
* @var array
*/
- protected $routeStack;
+ protected $routeStack = [];
/**
* List of added bootmanagers
* @var array
*/
- protected $bootManagers;
+ protected $bootManagers = [];
/**
* Csrf verifier class
@@ -64,11 +70,48 @@ class Router
* Get exception handlers
* @var array
*/
- protected $exceptionHandlers;
+ protected $exceptionHandlers = [];
+
+ /**
+ * List of loaded exception that has been loaded.
+ * Used to ensure that exception-handlers aren't loaded twice when rewriting route.
+ *
+ * @var array
+ */
+ protected $loadedExceptionHandlers = [];
+
+ /**
+ * Enable or disabled debugging
+ * @var bool
+ */
+ protected $debugEnabled = false;
+
+ /**
+ * The start time used when debugging is enabled
+ * @var float
+ */
+ protected $debugStartTime;
+
+ /**
+ * List containing all debug messages
+ * @var array
+ */
+ protected $debugList = [];
+
+ /**
+ * Contains any registered event-handler.
+ * @var array
+ */
+ protected $eventHandlers = [];
+
+ /**
+ * Class loader instance
+ * @var ClassLoader
+ */
+ protected $classLoader;
/**
* Router constructor.
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function __construct()
{
@@ -76,17 +119,29 @@ class Router
}
/**
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
+ * Resets the router by reloading request and clearing all routes and data.
*/
- public function reset()
+ public function reset(): void
{
- $this->processingRoute = false;
- $this->request = new Request();
+ $this->debugStartTime = microtime(true);
+ $this->isProcessingRoute = false;
+
+ try {
+ $this->request = new Request();
+ } catch (MalformedUrlException $e) {
+ $this->debug(sprintf('Invalid request-uri url: %s', $e->getMessage()));
+ }
+
$this->routes = [];
$this->bootManagers = [];
$this->routeStack = [];
$this->processedRoutes = [];
$this->exceptionHandlers = [];
+ $this->loadedExceptionHandlers = [];
+ $this->eventHandlers = [];
+ $this->debugList = [];
+ $this->csrfVerifier = null;
+ $this->classLoader = new ClassLoader();
}
/**
@@ -94,18 +149,22 @@ class Router
* @param IRoute $route
* @return IRoute
*/
- public function addRoute(IRoute $route)
+ public function addRoute(IRoute $route): IRoute
{
+ $this->fireEvents(EventHandler::EVENT_ADD_ROUTE, [
+ 'route' => $route,
+ ]);
+
/*
* If a route is currently being processed, that means that the route being added are rendered from the parent
* routes callback, so we add them to the stack instead.
*/
- if ($this->processingRoute === true) {
+ if ($this->isProcessingRoute === true) {
$this->routeStack[] = $route;
- return $route;
+ } else {
+ $this->routes[] = $route;
}
- $this->routes[] = $route;
return $route;
}
@@ -115,13 +174,14 @@ class Router
* @param IRoute $route
* @throws NotFoundHttpException
*/
- protected function renderAndProcess(IRoute $route) {
+ protected function renderAndProcess(IRoute $route): void
+ {
- $this->processingRoute = true;
- $route->renderRoute($this->request);
- $this->processingRoute = false;
+ $this->isProcessingRoute = true;
+ $route->renderRoute($this->request, $this);
+ $this->isProcessingRoute = false;
- if (count($this->routeStack) !== 0) {
+ if (\count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
@@ -139,21 +199,27 @@ class Router
* @param IGroupRoute|null $group
* @throws NotFoundHttpException
*/
- protected function processRoutes(array $routes, IGroupRoute $group = null)
+ protected function processRoutes(array $routes, ?IGroupRoute $group = null): void
{
+ $this->debug('Processing routes');
+
// Loop through each route-request
$exceptionHandlers = [];
// Stop processing routes if no valid route is found.
- if($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
+ if ($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
+ $this->debug('Halted route-processing as no valid route was found');
+
return;
}
- $url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath();
+ $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route IRoute */
foreach ($routes as $route) {
+ $this->debug('Processing route "%s"', \get_class($route));
+
if ($group !== null) {
/* Add the parent group */
$route->setGroup($group);
@@ -165,7 +231,7 @@ class Router
if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */
- if (count($route->getExceptionHandlers()) !== 0) {
+ if (\count($route->getExceptionHandlers()) !== 0) {
/** @noinspection AdditionOperationOnArraysInspection */
$exceptionHandlers += $route->getExceptionHandlers();
}
@@ -199,81 +265,143 @@ class Router
* @throws NotFoundHttpException
* @return void
*/
- public function loadRoutes()
+ public function loadRoutes(): void
{
+ $this->debug('Loading routes');
+
+ $this->fireEvents(EventHandler::EVENT_BOOT, [
+ 'bootmanagers' => $this->bootManagers,
+ ]);
+
/* Initialize boot-managers */
+
/* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) {
- $manager->boot($this->request);
+
+ $className = \get_class($manager);
+ $this->debug('Rendering bootmanager "%s"', $className);
+ $this->fireEvents(EventHandler::EVENT_RENDER_BOOTMANAGER, [
+ 'bootmanagers' => $this->bootManagers,
+ 'bootmanager' => $manager,
+ ]);
+
+ /* Render bootmanager */
+ $manager->boot($this, $this->request);
+
+ $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');
+ }
+
+ /**
+ * Start the routing
+ *
+ * @return string|null
+ * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
+ * @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
+ * @throws HttpException
+ * @throws \Exception
+ */
+ public function start(): ?string
+ {
+ $this->debug('Router starting');
+
+ $this->fireEvents(EventHandler::EVENT_INIT);
+
+ $this->loadRoutes();
+
+ if ($this->csrfVerifier !== null) {
+
+ $this->fireEvents(EventHandler::EVENT_RENDER_CSRF, [
+ 'csrfVerifier' => $this->csrfVerifier,
+ ]);
+
+ /* Verify csrf token for request */
+ $this->csrfVerifier->handle($this->request);
+ }
+
+ $output = $this->routeRequest();
+
+ $this->fireEvents(EventHandler::EVENT_LOAD, [
+ 'loadedRoutes' => $this->getRequest()->getLoadedRoutes(),
+ ]);
+
+ $this->debug('Routing complete');
+
+ return $output;
}
/**
* Routes the request
*
- * @param bool $rewrite
- * @return string|mixed
+ * @return string|null
* @throws HttpException
* @throws \Exception
*/
- public function routeRequest($rewrite = false)
+ public function routeRequest(): ?string
{
- $routeNotAllowed = false;
+ $this->debug('Routing request');
+
+ $methodNotAllowed = false;
try {
-
- if ($rewrite === false) {
- $this->loadRoutes();
-
- if ($this->csrfVerifier !== null) {
-
- /* Verify csrf token for request */
- $this->csrfVerifier->handle($this->request);
- }
- } else {
- $this->request->setHasRewrite(false);
- }
-
- $url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath();
+ $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $key => $route) {
+ $this->debug('Matching route "%s"', \get_class($route));
+
/* If the route matches */
if ($route->matchRoute($url, $this->request) === true) {
+ $this->fireEvents(EventHandler::EVENT_MATCH_ROUTE, [
+ 'route' => $route,
+ ]);
+
/* Check if request method matches */
- if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) {
- $routeNotAllowed = true;
+ 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;
continue;
}
- $route->loadMiddleware($this->request);
+ $this->fireEvents(EventHandler::EVENT_RENDER_MIDDLEWARES, [
+ 'route' => $route,
+ 'middlewares' => $route->getMiddlewares(),
+ ]);
- if ($this->hasRewrite($url) === true) {
- unset($this->processedRoutes[$key]);
-
- return $this->routeRequest(true);
- }
-
- /* Render route */
- $routeNotAllowed = false;
-
- $this->request->setLoadedRoute($route);
-
- $output = $route->renderRoute($this->request);
+ $route->loadMiddleware($this->request, $this);
+ $output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
}
- if ($this->hasRewrite($url) === true) {
- unset($this->processedRoutes[$key]);
+ $methodNotAllowed = false;
- return $this->routeRequest(true);
+ $this->request->addLoadedRoute($route);
+
+ $this->fireEvents(EventHandler::EVENT_RENDER_ROUTE, [
+ 'route' => $route,
+ ]);
+
+ $output = $route->renderRoute($this->request, $this);
+ if ($output !== null) {
+ return $output;
+ }
+
+ $output = $this->handleRouteRewrite($key, $url);
+ if ($output !== null) {
+ return $output;
}
}
}
@@ -282,12 +410,12 @@ class Router
$this->handleException($e);
}
- if ($routeNotAllowed === true) {
+ if ($methodNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod());
$this->handleException(new HttpException($message, 403));
}
- if ($this->request->getLoadedRoute() === null) {
+ if (\count($this->request->getLoadedRoutes()) === 0) {
$rewriteUrl = $this->request->getRewriteUrl();
@@ -297,136 +425,185 @@ class Router
$message = sprintf('Route not found: "%s"', $this->request->getUrl()->getPath());
}
- $this->handleException(new NotFoundHttpException($message, 404));
+ $this->debug($message);
+
+ return $this->handleException(new NotFoundHttpException($message, 404));
}
return null;
}
- protected function hasRewrite($url)
+ /**
+ * Handle route-rewrite
+ *
+ * @param string $key
+ * @param string $url
+ * @return string|null
+ * @throws HttpException
+ * @throws \Exception
+ */
+ protected function handleRouteRewrite($key, string $url): ?string
{
-
/* If the request has changed */
- if ($this->request->hasRewrite() === true) {
-
- if ($this->request->getRewriteRoute() !== null) {
- /* Render rewrite-route */
- $this->processedRoutes[] = $this->request->getRewriteRoute();
-
- return true;
- }
-
- if ($this->request->isRewrite($url) === false) {
-
- /* Render rewrite-url */
- $this->processedRoutes = array_values($this->processedRoutes);
-
- return true;
- }
+ if ($this->request->hasPendingRewrite() === false) {
+ return null;
}
- return false;
+ $route = $this->request->getRewriteRoute();
+
+ if ($route !== null) {
+ /* Add rewrite route */
+ $this->processedRoutes[] = $route;
+ }
+
+ if ($this->request->getRewriteUrl() !== $url) {
+ unset($this->processedRoutes[$key]);
+ $this->request->setHasPendingRewrite(false);
+
+ $this->fireEvents(EventHandler::EVENT_REWRITE, [
+ 'rewriteUrl' => $this->request->getRewriteUrl(),
+ 'rewriteRoute' => $this->request->getRewriteRoute(),
+ ]);
+
+ return $this->routeRequest();
+ }
+
+ return null;
}
/**
* @param \Exception $e
* @throws HttpException
* @throws \Exception
- * @return string
+ * @return string|null
*/
- protected function handleException(\Exception $e)
+ protected function handleException(\Exception $e): ?string
{
+ $this->debug('Starting exception handling for "%s"', \get_class($e));
+
+ $this->fireEvents(EventHandler::EVENT_LOAD_EXCEPTIONS, [
+ 'exception' => $e,
+ 'exceptionHandlers' => $this->exceptionHandlers,
+ ]);
+
/* @var $handler IExceptionHandler */
foreach ($this->exceptionHandlers as $key => $handler) {
- if (is_object($handler) === false) {
+ if (\is_object($handler) === false) {
$handler = new $handler();
}
+ $this->fireEvents(EventHandler::EVENT_RENDER_EXCEPTION, [
+ 'exception' => $e,
+ 'exceptionHandler' => $handler,
+ 'exceptionHandlers' => $this->exceptionHandlers,
+ ]);
+
+ $this->debug('Processing exception-handler "%s"', \get_class($handler));
+
if (($handler instanceof IExceptionHandler) === false) {
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
}
try {
+ $this->debug('Start rendering exception handler');
$handler->handleError($this->request, $e);
+ $this->debug('Finished rendering exception-handler');
- if ($this->request->hasRewrite() === true) {
- unset($this->exceptionHandlers[$key]);
- $this->exceptionHandlers = array_values($this->exceptionHandlers);
+ if (isset($this->loadedExceptionHandlers[$key]) === false && $this->request->hasPendingRewrite() === true) {
- return $this->routeRequest(true);
+ $this->loadedExceptionHandlers[$key] = $handler;
+
+ $this->debug('Exception handler contains rewrite, reloading routes');
+
+ $this->fireEvents(EventHandler::EVENT_REWRITE, [
+ 'rewriteUrl' => $this->request->getRewriteUrl(),
+ 'rewriteRoute' => $this->request->getRewriteRoute(),
+ ]);
+
+ if ($this->request->getRewriteRoute() !== null) {
+ $this->processedRoutes[] = $this->request->getRewriteRoute();
+ }
+
+ return $this->routeRequest();
}
} catch (\Exception $e) {
}
+
+ $this->debug('Finished processing');
}
+ $this->debug('Finished exception handling - exception not handled, throwing');
throw $e;
}
- public function arrayToParams(array $getParams = [], $includeEmpty = true)
- {
- if (count($getParams) !== 0) {
-
- if ($includeEmpty === false) {
- $getParams = array_filter($getParams, function ($item) {
- return (trim($item) !== '');
- });
- }
-
- return '?' . http_build_query($getParams);
- }
-
- return '';
- }
-
/**
* Find route by alias, class, callback or method.
*
* @param string $name
* @return ILoadableRoute|null
*/
- public function findRoute($name)
+ public function findRoute(string $name): ?ILoadableRoute
{
+ $this->debug('Finding route by name "%s"', $name);
+
+ $this->fireEvents(EventHandler::EVENT_FIND_ROUTE, [
+ 'name' => $name,
+ ]);
+
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
- if ($route->hasName($name)) {
+ if ($route->hasName($name) === true) {
+ $this->debug('Found route "%s" by name "%s"', $route->getUrl(), $name);
+
return $route;
}
/* Direct match to controller */
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) {
+ $this->debug('Found route "%s" by controller "%s"', $route->getUrl(), $name);
+
return $route;
}
/* Using @ is most definitely a controller@method or alias@method */
- if (is_string($name) === true && strpos($name, '@') !== false) {
- list($controller, $method) = array_map('strtolower', explode('@', $name));
+ if (\is_string($name) === true && strpos($name, '@') !== false) {
+ [$controller, $method] = array_map('strtolower', explode('@', $name));
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
+ $this->debug('Found route "%s" by controller "%s" and method "%s"', $route->getUrl(), $controller, $method);
+
return $route;
}
}
/* Check if callback matches (if it's not a function) */
- if (is_string($name) === true && is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && is_callable($route->getCallback()) === false) {
+ $callback = $route->getCallback();
+ if (\is_string($name) === true && \is_string($callback) === true && strpos($name, '@') !== false && strpos($callback, '@') !== false && \is_callable($callback) === false) {
/* Check if the entire callback is matching */
- if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) {
+ if (strpos($callback, $name) === 0 || strtolower($callback) === strtolower($name)) {
+ $this->debug('Found route "%s" by callback "%s"', $route->getUrl(), $name);
+
return $route;
}
/* Check if the class part of the callback matches (class@method) */
if (strtolower($name) === strtolower($route->getClass())) {
+ $this->debug('Found route "%s" by class "%s"', $route->getUrl(), $name);
+
return $route;
}
}
}
+ $this->debug('Route not found');
+
return null;
}
@@ -445,17 +622,26 @@ class Router
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
+ * @return Url
* @throws InvalidArgumentException
- * @return string
+ * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public function getUrl($name = null, $parameters = null, $getParams = null)
+ public function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url
{
- if ($getParams !== null && is_array($getParams) === false) {
+ $this->debug('Finding url', \func_get_args());
+
+ $this->fireEvents(EventHandler::EVENT_GET_URL, [
+ 'name' => $name,
+ 'parameters' => $parameters,
+ 'getParams' => $getParams,
+ ]);
+
+ if ($getParams !== null && \is_array($getParams) === false) {
throw new InvalidArgumentException('Invalid type for getParams. Must be array or null');
}
if ($name === '' && $parameters === '') {
- return '/';
+ return new Url('/');
}
/* Only merge $_GET when all parameters are null */
@@ -467,26 +653,34 @@ class Router
/* Return current route if no options has been specified */
if ($name === null && $parameters === null) {
- return $this->request->getUrl()->getPath() . $this->arrayToParams($getParams);
+ return $this->request
+ ->getUrlCopy()
+ ->setParams($getParams);
}
$loadedRoute = $this->request->getLoadedRoute();
/* If nothing is defined and a route is loaded we use that */
if ($name === null && $loadedRoute !== null) {
- return $loadedRoute->findUrl($loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams);
+ return $this->request
+ ->getUrlCopy()
+ ->setPath($loadedRoute->findUrl($loadedRoute->getMethod(), $parameters, $name))
+ ->setParams($getParams);
}
/* We try to find a match on the given name */
$route = $this->findRoute($name);
if ($route !== null) {
- return $route->findUrl($route->getMethod(), $parameters, $name) . $this->arrayToParams($getParams);
+ return $this->request
+ ->getUrlCopy()
+ ->setPath($route->findUrl($route->getMethod(), $parameters, $name))
+ ->setParams($getParams);
}
/* Using @ is most definitely a controller@method or alias@method */
- if (is_string($name) === true && strpos($name, '@') !== false) {
- list($controller, $method) = explode('@', $name);
+ if (\is_string($name) === true && strpos($name, '@') !== false) {
+ [$controller, $method] = explode('@', $name);
/* Loop through all the routes to see if we can find a match */
@@ -495,12 +689,18 @@ class Router
/* Check if the route contains the name/alias */
if ($route->hasName($controller) === true) {
- return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams);
+ return $this->request
+ ->getUrlCopy()
+ ->setPath($route->findUrl($method, $parameters, $name))
+ ->setParams($getParams);
}
/* Check if the route controller is equal to the name */
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($controller)) {
- return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams);
+ return $this->request
+ ->getUrlCopy()
+ ->setPath($route->findUrl($method, $parameters, $name))
+ ->setParams($getParams);
}
}
@@ -508,35 +708,47 @@ class Router
/* No result so we assume that someone is using a hardcoded url and join everything together. */
$url = trim(implode('/', array_merge((array)$name, (array)$parameters)), '/');
+ $url = (($url === '') ? '/' : '/' . $url . '/');
- return (($url === '') ? '/' : '/' . $url . '/') . $this->arrayToParams($getParams);
+ return $this->request
+ ->getUrlCopy()
+ ->setPath($url)
+ ->setParams($getParams);
}
/**
- * Get bootmanagers
+ * Get BootManagers
* @return array
*/
- public function getBootManagers()
+ public function getBootManagers(): array
{
return $this->bootManagers;
}
/**
- * Set bootmanagers
+ * Set BootManagers
+ *
* @param array $bootManagers
+ * @return static
*/
- public function setBootManagers(array $bootManagers)
+ public function setBootManagers(array $bootManagers): self
{
$this->bootManagers = $bootManagers;
+
+ return $this;
}
/**
- * Add bootmanager
+ * Add BootManager
+ *
* @param IRouterBootManager $bootManager
+ * @return static
*/
- public function addBootManager(IRouterBootManager $bootManager)
+ public function addBootManager(IRouterBootManager $bootManager): self
{
$this->bootManagers[] = $bootManager;
+
+ return $this;
}
/**
@@ -544,7 +756,7 @@ class Router
*
* @return array
*/
- public function getProcessedRoutes()
+ public function getProcessedRoutes(): array
{
return $this->processedRoutes;
}
@@ -552,7 +764,7 @@ class Router
/**
* @return array
*/
- public function getRoutes()
+ public function getRoutes(): array
{
return $this->routes;
}
@@ -561,9 +773,9 @@ class Router
* Set routes
*
* @param array $routes
- * @return static $this
+ * @return static
*/
- public function setRoutes(array $routes)
+ public function setRoutes(array $routes): self
{
$this->routes = $routes;
@@ -575,7 +787,7 @@ class Router
*
* @return Request
*/
- public function getRequest()
+ public function getRequest(): Request
{
return $this->request;
}
@@ -584,7 +796,7 @@ class Router
* Get csrf verifier class
* @return BaseCsrfVerifier
*/
- public function getCsrfVerifier()
+ public function getCsrfVerifier(): ?BaseCsrfVerifier
{
return $this->csrfVerifier;
}
@@ -595,11 +807,117 @@ class Router
* @param BaseCsrfVerifier $csrfVerifier
* @return static
*/
- public function setCsrfVerifier(BaseCsrfVerifier $csrfVerifier)
+ public function setCsrfVerifier(BaseCsrfVerifier $csrfVerifier): self
{
$this->csrfVerifier = $csrfVerifier;
return $this;
}
+ /**
+ * Set class loader
+ *
+ * @param IClassLoader $loader
+ * @return static
+ */
+ public function setClassLoader(IClassLoader $loader)
+ {
+ $this->classLoader = $loader;
+
+ return $this;
+ }
+
+ /**
+ * Get class loader
+ *
+ * @return ClassLoader
+ */
+ public function getClassLoader(): IClassLoader
+ {
+ return $this->classLoader;
+ }
+
+ /**
+ * Register event handler
+ *
+ * @param IEventHandler $handler
+ * @return static
+ */
+ public function addEventHandler(IEventHandler $handler): self
+ {
+ $this->eventHandlers[] = $handler;
+
+ return $this;
+ }
+
+ /**
+ * Get registered event-handler.
+ *
+ * @return array
+ */
+ public function getEventHandlers(): array
+ {
+ return $this->eventHandlers;
+ }
+
+ /**
+ * Fire event in event-handler.
+ *
+ * @param string $name
+ * @param array $arguments
+ */
+ protected function fireEvents($name, array $arguments = []): void
+ {
+ if (\count($this->eventHandlers) === 0) {
+ return;
+ }
+
+ /* @var IEventHandler $eventHandler */
+ foreach ($this->eventHandlers as $eventHandler) {
+ $eventHandler->fireEvents($this, $name, $arguments);
+ }
+ }
+
+ /**
+ * Add new debug message
+ * @param string $message
+ * @param array $args
+ */
+ public function debug(string $message, ...$args): void
+ {
+ if ($this->debugEnabled === false) {
+ return;
+ }
+
+ $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
+ $this->debugList[] = [
+ 'message' => vsprintf($message, $args),
+ 'time' => number_format(microtime(true) - $this->debugStartTime, 10),
+ 'trace' => end($trace),
+ ];
+ }
+
+ /**
+ * Enable or disables debugging
+ *
+ * @param bool $enabled
+ * @return static
+ */
+ public function setDebugEnabled(bool $enabled): self
+ {
+ $this->debugEnabled = $enabled;
+
+ return $this;
+ }
+
+ /**
+ * Get the list containing all debug messages.
+ *
+ * @return array
+ */
+ public function getDebugLog(): array
+ {
+ return $this->debugList;
+ }
+
}
\ No newline at end of file
diff --git a/src/Pecee/SimpleRouter/SimpleRouter.php b/src/Pecee/SimpleRouter/SimpleRouter.php
index 81b6014..b4faf62 100644
--- a/src/Pecee/SimpleRouter/SimpleRouter.php
+++ b/src/Pecee/SimpleRouter/SimpleRouter.php
@@ -10,15 +10,23 @@
namespace Pecee\SimpleRouter;
+use DI\Container;
use Pecee\Exceptions\InvalidArgumentException;
-use Pecee\Handlers\CallbackExceptionHandler;
+use Pecee\Http\Exceptions\MalformedUrlException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
+use Pecee\Http\Request;
use Pecee\Http\Response;
+use Pecee\Http\Url;
+use Pecee\SimpleRouter\ClassLoader\IClassLoader;
use Pecee\SimpleRouter\Exceptions\HttpException;
+use Pecee\SimpleRouter\Handlers\CallbackExceptionHandler;
+use Pecee\SimpleRouter\Handlers\IEventHandler;
+use Pecee\SimpleRouter\Route\IGroupRoute;
+use Pecee\SimpleRouter\Route\IPartialGroupRoute;
use Pecee\SimpleRouter\Route\IRoute;
-use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteController;
use Pecee\SimpleRouter\Route\RouteGroup;
+use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteResource;
use Pecee\SimpleRouter\Route\RouteUrl;
@@ -26,7 +34,7 @@ class SimpleRouter
{
/**
* Default namespace added to all routes
- * @var string
+ * @var string|null
*/
protected static $defaultNamespace;
@@ -43,13 +51,72 @@ class SimpleRouter
protected static $router;
/**
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
+ * Start routing
+ *
+ * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
+ * @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException
* @throws \Exception
*/
- public static function start()
+ public static function start(): void
{
- echo static::router()->routeRequest();
+ echo static::router()->start();
+ }
+
+ /**
+ * Start the routing an return array with debugging-information
+ *
+ * @return array
+ */
+ public static function startDebug(): array
+ {
+ $routerOutput = null;
+
+ try {
+ ob_start();
+ static::router()->setDebugEnabled(true);
+ static::start();
+ $routerOutput = ob_get_contents();
+ ob_end_clean();
+ } catch (\Exception $e) {
+
+ }
+
+ // Try to parse library version
+ $composerFile = \dirname(__DIR__, 3) . '/composer.lock';
+ $version = false;
+
+ if (is_file($composerFile) === true) {
+ $composerInfo = json_decode(file_get_contents($composerFile), true);
+
+ if (isset($composerInfo['packages']) === true && \is_array($composerInfo['packages']) === true) {
+ foreach ($composerInfo['packages'] as $package) {
+ if (isset($package['name']) === true && strtolower($package['name']) === 'pecee/simple-router') {
+ $version = $package['version'];
+ break;
+ }
+ }
+ }
+ }
+
+ $request = static::request();
+ $router = static::router();
+
+ return [
+ 'url' => $request->getUrl(),
+ 'method' => $request->getMethod(),
+ 'host' => $request->getHost(),
+ 'loaded_routes' => $request->getLoadedRoutes(),
+ 'all_routes' => $router->getRoutes(),
+ 'boot_managers' => $router->getBootManagers(),
+ 'csrf_verifier' => $router->getCsrfVerifier(),
+ 'log' => $router->getDebugLog(),
+ 'event_handlers' => $router->getEventHandlers(),
+ 'router_output' => $routerOutput,
+ 'library_version' => $version,
+ 'php_version' => PHP_VERSION,
+ 'server_params' => $request->getHeaders(),
+ ];
}
/**
@@ -57,7 +124,7 @@ class SimpleRouter
*
* @param string $defaultNamespace
*/
- public static function setDefaultNamespace($defaultNamespace)
+ public static function setDefaultNamespace(string $defaultNamespace): void
{
static::$defaultNamespace = $defaultNamespace;
}
@@ -66,21 +133,29 @@ class SimpleRouter
* Base CSRF verifier
*
* @param BaseCsrfVerifier $baseCsrfVerifier
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier)
+ public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier): void
{
static::router()->setCsrfVerifier($baseCsrfVerifier);
}
+ /**
+ * Add new event handler to the router
+ *
+ * @param IEventHandler $eventHandler
+ */
+ public static function addEventHandler(IEventHandler $eventHandler): void
+ {
+ static::router()->addEventHandler($eventHandler);
+ }
+
/**
* Boot managers allows you to alter the routes before the routing occurs.
* Perfect if you want to load pretty-urls from a file or database.
*
* @param IRouterBootManager $bootManager
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function addBootManager(IRouterBootManager $bootManager)
+ public static function addBootManager(IRouterBootManager $bootManager): void
{
static::router()->addBootManager($bootManager);
}
@@ -93,9 +168,8 @@ class SimpleRouter
* @param array|null $settings
*
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function get($url, $callback, array $settings = null)
+ public static function get(string $url, $callback, array $settings = null): IRoute
{
return static::match(['get'], $url, $callback, $settings);
}
@@ -107,9 +181,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function post($url, $callback, array $settings = null)
+ public static function post(string $url, $callback, array $settings = null): IRoute
{
return static::match(['post'], $url, $callback, $settings);
}
@@ -121,9 +194,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function put($url, $callback, array $settings = null)
+ public static function put(string $url, $callback, array $settings = null): IRoute
{
return static::match(['put'], $url, $callback, $settings);
}
@@ -135,9 +207,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function patch($url, $callback, array $settings = null)
+ public static function patch(string $url, $callback, array $settings = null): IRoute
{
return static::match(['patch'], $url, $callback, $settings);
}
@@ -149,9 +220,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function options($url, $callback, array $settings = null)
+ public static function options(string $url, $callback, array $settings = null): IRoute
{
return static::match(['options'], $url, $callback, $settings);
}
@@ -163,9 +233,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function delete($url, $callback, array $settings = null)
+ public static function delete(string $url, $callback, array $settings = null): IRoute
{
return static::match(['delete'], $url, $callback, $settings);
}
@@ -176,12 +245,11 @@ class SimpleRouter
* @param array $settings
* @param \Closure $callback
* @return RouteGroup
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException
*/
- public static function group(array $settings = [], \Closure $callback)
+ public static function group(array $settings = [], \Closure $callback): IGroupRoute
{
- if (is_callable($callback) === false) {
+ if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
@@ -202,12 +270,11 @@ class SimpleRouter
* @param \Closure $callback
* @param array $settings
* @return RoutePartialGroup
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException
*/
- public static function partialGroup($url, \Closure $callback, array $settings = [])
+ public static function partialGroup(string $url, \Closure $callback, array $settings = []): IPartialGroupRoute
{
- if (is_callable($callback) === false) {
+ if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
@@ -230,9 +297,8 @@ class SimpleRouter
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function basic($url, $callback, array $settings = null)
+ public static function basic(string $url, $callback, array $settings = null): IRoute
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
@@ -246,9 +312,8 @@ class SimpleRouter
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function form($url, $callback, array $settings = null)
+ public static function form(string $url, $callback, array $settings = null): IRoute
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
@@ -261,9 +326,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function match(array $requestMethods, $url, $callback, array $settings = null)
+ public static function match(array $requestMethods, string $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
@@ -285,9 +349,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function all($url, $callback, array $settings = null)
+ public static function all(string $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route);
@@ -308,9 +371,8 @@ class SimpleRouter
* @param string $controller
* @param array|null $settings
* @return RouteController|IRoute
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function controller($url, $controller, array $settings = null)
+ public static function controller(string $url, $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route);
@@ -331,9 +393,8 @@ class SimpleRouter
* @param string $controller
* @param array|null $settings
* @return RouteResource|IRoute
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function resource($url, $controller, array $settings = null)
+ public static function resource(string $url, $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route);
@@ -352,9 +413,8 @@ class SimpleRouter
*
* @param \Closure $callback
* @return CallbackExceptionHandler $callbackHandler
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function error(\Closure $callback)
+ public static function error(\Closure $callback): CallbackExceptionHandler
{
$routes = static::router()->getRoutes();
@@ -385,22 +445,30 @@ class SimpleRouter
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
- * @throws \Pecee\Exceptions\InvalidArgumentException
- * @return string
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
+ * @return Url
*/
- public static function getUrl($name = null, $parameters = null, $getParams = null)
+ public static function getUrl(?string $name = null, $parameters = null, ?array $getParams = null): Url
{
- return static::router()->getUrl($name, $parameters, $getParams);
+ try {
+ return static::router()->getUrl($name, $parameters, $getParams);
+ } catch (\Exception $e) {
+ try {
+ return new Url('/');
+ } catch (MalformedUrlException $e) {
+
+ }
+ }
+
+ // This will never happen...
+ return null;
}
/**
* Get the request
*
* @return \Pecee\Http\Request
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function request()
+ public static function request(): Request
{
return static::router()->getRequest();
}
@@ -409,9 +477,8 @@ class SimpleRouter
* Get the response object
*
* @return Response
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function response()
+ public static function response(): Response
{
if (static::$response === null) {
static::$response = new Response(static::request());
@@ -424,9 +491,8 @@ class SimpleRouter
* Returns the router instance
*
* @return Router
- * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
- public static function router()
+ public static function router(): Router
{
if (static::$router === null) {
static::$router = new Router();
@@ -441,14 +507,14 @@ class SimpleRouter
* @param IRoute $route
* @return IRoute
*/
- public static function addDefaultNamespace(IRoute $route)
+ public static function addDefaultNamespace(IRoute $route): IRoute
{
if (static::$defaultNamespace !== null) {
$callback = $route->getCallback();
/* Only add default namespace on relative callbacks */
- if ($callback === null || (is_string($callback) === true && $callback[0] !== '\\')) {
+ if ($callback === null || (\is_string($callback) === true && $callback[0] !== '\\')) {
$namespace = static::$defaultNamespace;
@@ -467,10 +533,24 @@ class SimpleRouter
}
/**
- * Get default namespace
- * @return string
+ * Enable or disable dependency injection
+ *
+ * @param Container $container
+ * @return IClassLoader
*/
- public static function getDefaultNamespace()
+ public static function enableDependencyInjection(Container $container): IClassLoader
+ {
+ return static::router()
+ ->getClassLoader()
+ ->useDependencyInjection(true)
+ ->setContainer($container);
+ }
+
+ /**
+ * Get default namespace
+ * @return string|null
+ */
+ public static function getDefaultNamespace(): ?string
{
return static::$defaultNamespace;
}
diff --git a/test/Dummy/Handler/ExceptionHandlerFirst.php b/test/Dummy/Handler/ExceptionHandlerFirst.php
deleted file mode 100644
index 8a5f807..0000000
--- a/test/Dummy/Handler/ExceptionHandlerFirst.php
+++ /dev/null
@@ -1,14 +0,0 @@
-setUrl('/');
- return $request;
- }
-
-}
\ No newline at end of file
diff --git a/test/Dummy/Handler/ExceptionHandlerSecond.php b/test/Dummy/Handler/ExceptionHandlerSecond.php
deleted file mode 100644
index d629a03..0000000
--- a/test/Dummy/Handler/ExceptionHandlerSecond.php
+++ /dev/null
@@ -1,14 +0,0 @@
-setUrl('/');
- return $request;
- }
-
-}
\ No newline at end of file
diff --git a/test/Dummy/ResourceController.php b/test/Dummy/ResourceController.php
deleted file mode 100644
index 8536563..0000000
--- a/test/Dummy/ResourceController.php
+++ /dev/null
@@ -1,39 +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/test/Dummy/DummyController.php b/tests/Pecee/SimpleRouter/Dummy/DummyController.php
similarity index 100%
rename from test/Dummy/DummyController.php
rename to tests/Pecee/SimpleRouter/Dummy/DummyController.php
diff --git a/test/Dummy/DummyMiddleware.php b/tests/Pecee/SimpleRouter/Dummy/DummyMiddleware.php
similarity index 61%
rename from test/Dummy/DummyMiddleware.php
rename to tests/Pecee/SimpleRouter/Dummy/DummyMiddleware.php
index 2b5bd32..20f6fb8 100644
--- a/test/Dummy/DummyMiddleware.php
+++ b/tests/Pecee/SimpleRouter/Dummy/DummyMiddleware.php
@@ -1,11 +1,11 @@
getMessage();
}
diff --git a/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerFirst.php b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerFirst.php
new file mode 100644
index 0000000..ca72071
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerFirst.php
@@ -0,0 +1,13 @@
+setUrl(new \Pecee\Http\Url('/'));
+ }
+
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerSecond.php b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerSecond.php
new file mode 100644
index 0000000..274bd3c
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerSecond.php
@@ -0,0 +1,13 @@
+setUrl(new \Pecee\Http\Url('/'));
+ }
+
+}
\ No newline at end of file
diff --git a/test/Dummy/Handler/ExceptionHandlerThird.php b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerThird.php
similarity index 64%
rename from test/Dummy/Handler/ExceptionHandlerThird.php
rename to tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerThird.php
index 15923ec..793746a 100644
--- a/test/Dummy/Handler/ExceptionHandlerThird.php
+++ b/tests/Pecee/SimpleRouter/Dummy/Handler/ExceptionHandlerThird.php
@@ -1,8 +1,8 @@
routes = $routes;
+ $this->aliasUrl = $aliasUrl;
+ }
+
+ /**
+ * 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
+ {
+ foreach ($this->routes as $url) {
+ // If the current url matches the rewrite url, we use our custom route
+
+ if ($request->getUrl()->contains($url) === true) {
+ $request->setRewriteUrl($this->aliasUrl);
+ }
+
+ }
+ }
+}
\ No newline at end of file
diff --git a/test/Dummy/Middlewares/RewriteMiddleware.php b/tests/Pecee/SimpleRouter/Dummy/Middleware/RewriteMiddleware.php
similarity index 79%
rename from test/Dummy/Middlewares/RewriteMiddleware.php
rename to tests/Pecee/SimpleRouter/Dummy/Middleware/RewriteMiddleware.php
index 7bd1fef..f107bbd 100644
--- a/test/Dummy/Middlewares/RewriteMiddleware.php
+++ b/tests/Pecee/SimpleRouter/Dummy/Middleware/RewriteMiddleware.php
@@ -5,7 +5,7 @@ use Pecee\Http\Request;
class RewriteMiddleware implements IMiddleware {
- public function handle(Request $request) {
+ public function handle(Request $request) : void {
$request->setRewriteCallback(function() {
return 'ok';
diff --git a/tests/Pecee/SimpleRouter/Dummy/ResourceController.php b/tests/Pecee/SimpleRouter/Dummy/ResourceController.php
new file mode 100644
index 0000000..0a70e6f
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/Dummy/ResourceController.php
@@ -0,0 +1,46 @@
+refresh();
+ }
+
+ /**
+ * Refresh existing token
+ */
+ public function refresh(): void
+ {
+ $this->token = uniqid('', false);
+ }
+
+ /**
+ * Validate valid CSRF token
+ *
+ * @param string $token
+ * @return bool
+ */
+ public function validate(string $token): bool
+ {
+ return ($token === $this->token);
+ }
+
+ /**
+ * Get token token
+ *
+ * @param string|null $defaultValue
+ * @return string|null
+ */
+ public function getToken(?string $defaultValue = null): ?string
+ {
+ return $this->token ?? $defaultValue;
+ }
+}
\ No newline at end of file
diff --git a/tests/Pecee/SimpleRouter/EventHandlerTest.php b/tests/Pecee/SimpleRouter/EventHandlerTest.php
new file mode 100644
index 0000000..8fa873d
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/EventHandlerTest.php
@@ -0,0 +1,107 @@
+register(EventHandler::EVENT_ALL, function (EventArgument $arg) use (&$events) {
+ $key = \array_search($arg->getEventName(), $events, true);
+ unset($events[$key]);
+ });
+
+ TestRouter::addEventHandler($eventHandler);
+
+ // Add rewrite
+ TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
+
+ // Trigger rewrite
+ $request->setRewriteUrl('/');
+
+ });
+
+ TestRouter::get('/', 'DummyController@method1')->name('home');
+
+ // Trigger findRoute
+ TestRouter::router()->findRoute('home');
+
+ // Trigger getUrl
+ TestRouter::router()->getUrl('home');
+
+ // Add csrf-verifier
+ $csrfVerifier = new \Pecee\Http\Middleware\BaseCsrfVerifier();
+ $csrfVerifier->setTokenProvider(new SilentTokenProvider());
+ TestRouter::csrfVerifier($csrfVerifier);
+
+ // Add boot-manager
+ TestRouter::addBootManager(new TestBootManager([
+ '/test',
+ ], '/'));
+
+ // Start router
+ TestRouter::debug('/non-existing');
+
+ $this->assertEquals($events, []);
+ }
+
+ public function testAllEvent()
+ {
+
+ $status = false;
+
+ $eventHandler = new EventHandler();
+ $eventHandler->register(EventHandler::EVENT_ALL, function (EventArgument $arg) use (&$status) {
+ $status = true;
+ });
+
+ TestRouter::addEventHandler($eventHandler);
+
+ TestRouter::get('/', 'DummyController@method1');
+ TestRouter::debug('/');
+
+ // All event should fire for each other event
+ $this->assertEquals(true, $status);
+ }
+
+ public function testPrefixEvent()
+ {
+
+ $eventHandler = new EventHandler();
+ $eventHandler->register(EventHandler::EVENT_ADD_ROUTE, function (EventArgument $arg) use (&$status) {
+
+ if ($arg->route instanceof \Pecee\SimpleRouter\Route\LoadableRoute) {
+ $arg->route->prependUrl('/local-path');
+ }
+
+ });
+
+ TestRouter::addEventHandler($eventHandler);
+
+ $status = false;
+
+ TestRouter::get('/', function () use (&$status) {
+ $status = true;
+ });
+
+ TestRouter::debug('/local-path');
+
+ $this->assertTrue($status);
+
+ }
+
+}
\ No newline at end of file
diff --git a/test/GroupTest.php b/tests/Pecee/SimpleRouter/GroupTest.php
similarity index 85%
rename from test/GroupTest.php
rename to tests/Pecee/SimpleRouter/GroupTest.php
index 29f89e0..ce79b26 100644
--- a/test/GroupTest.php
+++ b/tests/Pecee/SimpleRouter/GroupTest.php
@@ -2,18 +2,16 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
-require_once 'Helpers/TestRouter.php';
-class GroupTest extends PHPUnit_Framework_TestCase
+class GroupTest extends \PHPUnit\Framework\TestCase
{
- protected $result;
public function testGroupLoad()
{
- $this->result = false;
+ $result = false;
- TestRouter::group(['prefix' => '/group'], function () {
- $this->result = true;
+ TestRouter::group(['prefix' => '/group'], function () use(&$result) {
+ $result = true;
});
try {
@@ -21,7 +19,7 @@ class GroupTest extends PHPUnit_Framework_TestCase
} catch(\Exception $e) {
}
- $this->assertTrue($this->result);
+ $this->assertTrue($result);
}
public function testNestedGroup()
@@ -37,6 +35,7 @@ class GroupTest extends PHPUnit_Framework_TestCase
TestRouter::debug('/api/v1/test', 'get');
+ $this->assertTrue(true);
}
public function testMultipleRoutes()
@@ -61,6 +60,8 @@ class GroupTest extends PHPUnit_Framework_TestCase
});
TestRouter::debug('/my/match', 'get');
+
+ $this->assertTrue(true);
}
public function testUrls()
diff --git a/tests/Pecee/SimpleRouter/InputHandlerTest.php b/tests/Pecee/SimpleRouter/InputHandlerTest.php
new file mode 100644
index 0000000..7cdebc3
--- /dev/null
+++ b/tests/Pecee/SimpleRouter/InputHandlerTest.php
@@ -0,0 +1,35 @@
+assertEquals(true, true);
+ }
+
+ public function testPost()
+ {
+ $this->assertEquals(true, true);
+ }
+
+ public function testFile()
+ {
+ $this->assertEquals(true, true);
+ }
+
+ public function testFiles()
+ {
+ $this->assertEquals(true, true);
+ }
+
+ public function testAll()
+ {
+ $this->assertEquals(true, true);
+ }
+
+}
\ No newline at end of file
diff --git a/test/MiddlewareTest.php b/tests/Pecee/SimpleRouter/MiddlewareTest.php
similarity index 83%
rename from test/MiddlewareTest.php
rename to tests/Pecee/SimpleRouter/MiddlewareTest.php
index d3c4dba..0183c59 100644
--- a/test/MiddlewareTest.php
+++ b/tests/Pecee/SimpleRouter/MiddlewareTest.php
@@ -3,13 +3,12 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
-require_once 'Helpers/TestRouter.php';
-class MiddlewareTest extends PHPUnit_Framework_TestCase
+class MiddlewareTest extends \PHPUnit\Framework\TestCase
{
public function testMiddlewareFound()
{
- $this->setExpectedException(MiddlewareLoadedException::class);
+ $this->expectException(MiddlewareLoadedException::class);
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
@@ -29,6 +28,8 @@ class MiddlewareTest extends PHPUnit_Framework_TestCase
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
+
+ $this->assertTrue(true);
}
}
\ No newline at end of file
diff --git a/test/RouterCallbackExceptionHandlerTest.php b/tests/Pecee/SimpleRouter/RouterCallbackExceptionHandlerTest.php
similarity index 69%
rename from test/RouterCallbackExceptionHandlerTest.php
rename to tests/Pecee/SimpleRouter/RouterCallbackExceptionHandlerTest.php
index de21d2a..bf6514f 100644
--- a/test/RouterCallbackExceptionHandlerTest.php
+++ b/tests/Pecee/SimpleRouter/RouterCallbackExceptionHandlerTest.php
@@ -2,15 +2,14 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
-require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
-require_once 'Helpers/TestRouter.php';
+require_once 'Dummy/Exception/ExceptionHandlerException.php';
-class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
+class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
{
public function testCallbackExceptionHandler()
{
- $this->setExpectedException(ExceptionHandlerException::class);
+ $this->expectException(ExceptionHandlerException::class);
// Match normal route on alias
TestRouter::get('/my-new-url', 'DummyController@method2');
@@ -22,6 +21,8 @@ class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
TestRouter::debugNoReset('/404-url', 'get');
TestRouter::router()->reset();
+
+ $this->assertTrue(true);
}
}
\ No newline at end of file
diff --git a/test/RouterControllerTest.php b/tests/Pecee/SimpleRouter/RouterControllerTest.php
similarity index 89%
rename from test/RouterControllerTest.php
rename to tests/Pecee/SimpleRouter/RouterControllerTest.php
index 3c39bc2..fff6566 100644
--- a/test/RouterControllerTest.php
+++ b/tests/Pecee/SimpleRouter/RouterControllerTest.php
@@ -1,9 +1,8 @@
setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
+ $this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
diff --git a/test/RouterRouteTest.php b/tests/Pecee/SimpleRouter/RouterRouteTest.php
similarity index 82%
rename from test/RouterRouteTest.php
rename to tests/Pecee/SimpleRouter/RouterRouteTest.php
index c503b28..8e3caea 100644
--- a/test/RouterRouteTest.php
+++ b/tests/Pecee/SimpleRouter/RouterRouteTest.php
@@ -2,32 +2,30 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
-require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
-require_once 'Helpers/TestRouter.php';
+require_once 'Dummy/Exception/ExceptionHandlerException.php';
-class RouterRouteTest extends PHPUnit_Framework_TestCase
+class RouterRouteTest extends \PHPUnit\Framework\TestCase
{
- protected $result = false;
-
public function testMultiParam()
{
- TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) {
+ $result = false;
+ TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) use(&$result) {
if ($param1 === 'param1' && $param2 === 'param2') {
- $this->result = true;
+ $result = true;
}
});
TestRouter::debug('/test-param1-param2', 'get');
- $this->assertTrue($this->result);
+ $this->assertTrue($result);
}
public function testNotFound()
{
- $this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
+ $this->expectException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1');
TestRouter::debug('/test-param1-param2', 'post');
}
@@ -36,24 +34,32 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
+
+ $this->assertTrue(true);
}
public function testPost()
{
TestRouter::post('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'post');
+
+ $this->assertTrue(true);
}
public function testPut()
{
TestRouter::put('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'put');
+
+ $this->assertTrue(true);
}
public function testDelete()
{
TestRouter::delete('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'delete');
+
+ $this->assertTrue(true);
}
public function testMethodNotAllowed()
@@ -85,37 +91,37 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
public function testDomainAllowedRoute()
{
- $this->result = false;
+ $result = false;
+ TestRouter::request()->setHost('hello.world.com');
- TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
- TestRouter::get('/test', function ($subdomain = null) {
- $this->result = ($subdomain === 'hello');
+ TestRouter::group(['domain' => '{subdomain}.world.com'], function () use(&$result) {
+ TestRouter::get('/test', function ($subdomain = null) use(&$result) {
+ $result = ($subdomain === 'hello');
});
});
- TestRouter::request()->setHost('hello.world.com');
+
TestRouter::debug('/test', 'get');
- $this->assertTrue($this->result);
+ $this->assertTrue($result);
}
public function testDomainNotAllowedRoute()
{
- $this->result = false;
+ TestRouter::request()->setHost('other.world.com');
- TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
- TestRouter::get('/test', function ($subdomain = null) {
- $this->result = ($subdomain === 'hello');
+ $result = false;
+
+ TestRouter::group(['domain' => '{subdomain}.world.com'], function () use(&$result) {
+ TestRouter::get('/test', function ($subdomain = null) use(&$result) {
+ $result = ($subdomain === 'hello');
});
});
- TestRouter::request()->setHost('other.world.com');
-
-
TestRouter::debug('/test', 'get');
- $this->assertFalse($this->result);
+ $this->assertFalse($result);
}
@@ -123,6 +129,8 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
TestRouter::debug('/my/custom-path', 'get');
+
+ $this->assertTrue(true);
}
public function testParameterDefaultValue() {
diff --git a/test/RouterUrlTest.php b/tests/Pecee/SimpleRouter/RouterUrlTest.php
similarity index 98%
rename from test/RouterUrlTest.php
rename to tests/Pecee/SimpleRouter/RouterUrlTest.php
index f7d986d..78f9e1a 100644
--- a/test/RouterUrlTest.php
+++ b/tests/Pecee/SimpleRouter/RouterUrlTest.php
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
-require_once 'Helpers/TestRouter.php';
-class RouterUrlTest extends PHPUnit_Framework_TestCase
+class RouterUrlTest extends \PHPUnit\Framework\TestCase
{
public function testIssue253()
@@ -32,21 +31,22 @@ class RouterUrlTest extends PHPUnit_Framework_TestCase
{
// 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::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
+
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
+ TestRouter::debugNoReset('/test/Dermatología');
+ $parameters = TestRouter::request()->getLoadedRoute()->getParameters();
+
+ $this->assertEquals('Dermatología', $parameters['param']);
+
// Test danish characters
TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
TestRouter::debugNoReset('/kategori/økse', 'get');
+
$this->assertEquals('/kategori/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
- TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
- TestRouter::debugNoReset('/test/Dermatología');
-
- $parameters = TestRouter::request()->getLoadedRoute()->getParameters();
-
- $this->assertEquals('Dermatología', $parameters['param']);
-
TestRouter::router()->reset();
}
diff --git a/test/Helpers/TestRouter.php b/tests/TestRouter.php
similarity index 82%
rename from test/Helpers/TestRouter.php
rename to tests/TestRouter.php
index 60f820c..a6a5321 100644
--- a/test/Helpers/TestRouter.php
+++ b/tests/TestRouter.php
@@ -5,8 +5,10 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
public static function debugNoReset($testUrl, $testMethod = 'get')
{
- static::request()->setUrl($testUrl);
- static::request()->setMethod($testMethod);
+ $request = static::request();
+
+ $request->setUrl((new \Pecee\Http\Url($testUrl))->setHost('local.unitTest'));
+ $request->setMethod($testMethod);
static::start();
}
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
new file mode 100644
index 0000000..22f8cd2
--- /dev/null
+++ b/tests/bootstrap.php
@@ -0,0 +1,4 @@
+where(['name' => '[\w]+']);
+$debugInfo = SimpleRouter::startDebug();
+echo sprintf('%s
', var_export($debugInfo, true));
+exit;
\ No newline at end of file