v4-development sync

This commit is contained in:
DeveloperMarius
2021-03-23 15:42:44 +01:00
26 changed files with 531 additions and 309 deletions
-1
View File
@@ -1,4 +1,3 @@
composer.lock
vendor/
tests/tmp/*
.idea/
+18 -6
View File
@@ -1,13 +1,25 @@
sudo: false
language: php
php:
- 7.1
- 7.4.2
before_script:
- curl -sS http://getcomposer.org/installer | php
- php composer.phar install --prefer-source --no-interaction
- mkdir -p _clover
- ls -al
script:
- ./vendor/bin/phpunit
- ./vendor/phpunit/phpunit/phpunit --configuration ./phpunit.xml ./tests
install:
# Install composer packages
- travis_retry composer install --no-interaction --no-suggest
# Install coveralls.phar
- wget -c -nc --retry-connrefused --tries=0 https://github.com/php-coveralls/php-coveralls/releases/download/v2.0.0/php-coveralls.phar -O coveralls.phar
- chmod +x coveralls.phar
- php coveralls.phar --version
after_success:
# Submit coverage report to Coveralls servers, see .coveralls.yml
- travis_retry php coveralls.phar -v
# Submit coverage report to codecov.io
- bash <(curl -s https://codecov.io/bash)
+126 -88
View File
@@ -14,8 +14,7 @@ SimpleRouter::get('/', function() {
### Support the project
If you like simple-router and wish to see the continued development and maintenance of the project,
please consider showing your support by buying me a coffee. Supporters will be listed under the credits section of this documentation.
If you like simple-router and wish to see the continued development and maintenance of the project, please consider showing your support by buying me a coffee. Supporters will be listed under the credits section of this documentation.
You can donate any amount of your choice by [clicking here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NNX4D2RUSALCN).
@@ -52,9 +51,6 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Partial groups](#partial-groups)
- [Form Method Spoofing](#form-method-spoofing)
- [Accessing The Current Route](#accessing-the-current-route)
- [Dependency injection](#dependency-injection)
- [Enabling dependency injection](#enabling-dependency-injection)
- [More reading](#more-reading)
- [Other examples](#other-examples)
- [CSRF-protection](#csrf-protection)
- [Adding CSRF-verifier](#adding-csrf-verifier)
@@ -86,10 +82,13 @@ You can donate any amount of your choice by [clicking here](https://www.paypal.c
- [Registering new event](#registering-new-event)
- [Custom EventHandlers](#custom-eventhandlers)
- [Advanced](#advanced)
- [Disable multiple route rendering](#disable-multiple-route-rendering)
- [Url rewriting](#url-rewriting)
- [Changing current route](#changing-current-route)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Adding routes manually](#adding-routes-manually)
- [Custom class-loader](#custom-class-loader)
- [Integrating with php-di](#Integrating-with-php-di)
- [Parameters](#parameters)
- [Extending](#extending)
- [Help and support](#help-and-support)
@@ -251,6 +250,7 @@ To add `favicon.ico` to the IIS ignore-list, add the following line to the `<con
```
You can also make one exception for files with some extensions:
```
<add input="{REQUEST_FILENAME}" pattern="\.ico|\.png|\.css|\.jpg" negate="true" ignoreCase="true" />
```
@@ -258,6 +258,7 @@ You can also make one exception for files with some extensions:
If you are using `$_SERVER['ORIG_PATH_INFO']`, you will get `\index.php\` as part of the returned value.
**Example:**
```
/index.php/test/mypage.php
```
@@ -696,88 +697,6 @@ SimpleRouter::request()->getLoadedRoute();
request()->getLoadedRoute();
```
## Dependency injection
simple-router supports dependency injection using the [`php-di`](http://php-di.org/) library.
Dependency injection allows the framework to automatically "inject" (load) classes added as parameters. This can simplify your code, as you can avoid creating new instances of objects you are using often in your `Controllers` etc.
Here's a basic example of a controller class using dependency injection:
```php
namespace Demo\Controllers;
class DefaultController {
public function login(User $user): string
{
// ...
}
}
```
The example above will automatically create a new instance of the `User` from the `$user` parameter. This means that the `$user` class contains a new instance of the `User` class and we won't need to create a new instance our self.
**WARNING:** dependency injection can have some negative impact in performance. If you experience any performance issues, we recommend disabling this functionality.
### Enabling dependency injection
Dependency injection is disabled per default to avoid any performance issues.
Before enabling dependency injection, we recommend that you read the [Container configuration](http://php-di.org/doc/container-configuration.html) section of the php-di documentation. This section covers how to configure php-di to different environments and speed-up the performance.
#### Enabling for development environment
The example below should ONLY be used on a development environment.
```php
// Create our new php-di container
$container = (new \DI\ContainerBuilder())
->useAutowiring(true)
->build();
// Add our container to simple-router and enable dependency injection
SimpleRouter::enableDependencyInjection($container);
```
Please check the [More reading](#more-reading) section of the documentation for useful php-di links and tutorials.
#### Enabling for production environment
The example below compiles the injections, which can help speed up performance.
**Note:** You should change the `$cacheDir` to a cache-storage within your project.
```php
// Cache directory
$cacheDir = sys_get_temp_dir('simple-router');
// Create our new php-di container
$container = (new \DI\ContainerBuilder())
->enableCompilation($cacheDir)
->writeProxiesToFile(true, $cacheDir . '/proxies')
->useAutowiring(true)
->build();
// Add our container to simple-router and enable dependency injection
SimpleRouter::enableDependencyInjection($container);
```
Please check the [More reading](#more-reading) section of the documentation for useful php-di links and tutorials.
### More reading
For more information about dependency injection, configuration and settings - we recommend that you check the php-di documentation or some of the useful links we've gathered below.
#### Useful links
- [php-di documentation](http://php-di.org/doc/)
- [Understanding dependency injection](http://php-di.org/doc/understanding-di.html)
- [Best practices guide](http://php-di.org/doc/best-practices.html)
- [Configuring the container](http://php-di.org/doc/container-configuration.html)
- [Definitions](http://php-di.org/doc/definition.html)
## Other examples
You can find many more examples in the `routes.php` example-file below:
@@ -1444,6 +1363,12 @@ class DatabaseDebugHandler implements IEventHandler
# Advanced
## Disable multiple route rendering
By default the router will try to execute all routes that matches a given url. To stop the router from executing any further routes any method can return a value.
This behavior can be easily disabled by setting `SimpleRouter::enableMultiRouteRendering(false)` in your `routes.php` file. This is the same behavior as version 3 and below.
## Url rewriting
### Changing current route
@@ -1495,7 +1420,7 @@ class CustomRouterRules implement IRouterBootManager
// If the current url matches the rewrite url, we use our custom route
if($request->getUrl()->getPath() === $url) {
if($request->getUrl()->contains($url)) {
$request->setRewriteUrl($rule);
}
}
@@ -1543,6 +1468,119 @@ $route->setPrefix('v1');
$router->addRoute($route);
```
## Custom class loader
You can easily extend simple-router to support custom injection frameworks like php-di by taking advantage of the ability to add your custom class-loader.
Class-loaders must inherit the `IClassLoader` interface.
**Example:**
```php
class MyCustomClassLoader implements IClassLoader
{
/**
* Load class
*
* @param string $class
* @return object
* @throws NotFoundHttpException
*/
public function loadClass(string $class)
{
if (\class_exists($class) === false) {
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
}
return new $class();
}
/**
* Load closure
*
* @param Callable $closure
* @param array $parameters
* @return mixed
*/
public function loadClosure(Callable $closure, array $parameters)
{
return \call_user_func_array($closure, $parameters);
}
}
```
Next, we need to configure our `routes.php` so the router uses our `MyCustomClassLoader` class for loading classes. This can be done by adding the following line to your `routes.php` file.
```php
SimpleRouter::setCustomClassLoader(new MyCustomClassLoader());
```
### Integrating with php-di
php-di support was discontinued by version 4.3, however you can easily add it again by creating your own class-loader like the example below:
```php
class MyCustomClassLoader implements IClassLoader
{
protected $container;
public function __construct()
{
// Create our new php-di container
$container = (new \DI\ContainerBuilder())
->useAutowiring(true)
->build();
}
/**
* Load class
*
* @param string $class
* @return object
* @throws NotFoundHttpException
*/
public function loadClass(string $class)
{
if (class_exists($class) === false) {
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
}
if ($this->container !== null) {
try {
return $this->container->get($class);
} catch (\Exception $e) {
throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
return new $class();
}
/**
* Load closure
*
* @param Callable $closure
* @param array $parameters
* @return mixed
*/
public function loadClosure(Callable $closure, array $parameters)
{
if ($this->container !== null) {
try {
return $this->container->call($closure, $parameters);
} catch (\Exception $e) {
throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
return \call_user_func_array($closure, $parameters);
}
}
```
## Parameters
This section contains advanced tips & tricks on extending the usage for parameters.
+3 -4
View File
@@ -27,12 +27,11 @@
}
],
"require": {
"php": ">=7.3",
"ext-json": "*",
"php-di/php-di": "^6.0"
"php": ">=7.1",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "^8.5",
"phpunit/phpunit": "^8.0",
"mockery/mockery": "^1"
},
"scripts": {
+1 -1
View File
@@ -15,7 +15,7 @@ interface IInputItem
public function getValue();
public function setValue(string $value): self;
public function setValue($value): self;
public function __toString(): string;
+3 -3
View File
@@ -261,16 +261,16 @@ class InputFile implements IInputItem
return $this->getTmpName();
}
public function getValue(): ?string
public function getValue()
{
return $this->getFilename();
}
/**
* @param string $value
* @param mixed $value
* @return static
*/
public function setValue(string $value): IInputItem
public function setValue($value): IInputItem
{
$this->filename = $value;
+1 -1
View File
@@ -319,7 +319,7 @@ class InputHandler
public function all(array $filter = []): array
{
$output = $this->originalParams + $this->originalPost + $this->originalFile;
$output = (\count($filter) > 0) ? array_intersect_key($output, array_flip($filter)) : $output;
$output = (\count($filter) > 0) ? \array_intersect_key($output, \array_flip($filter)) : $output;
foreach ($filter as $filterKey) {
if (array_key_exists($filterKey, $output) === false) {
+2 -2
View File
@@ -62,10 +62,10 @@ class InputItem implements IInputItem, \IteratorAggregate
/**
* Set input value
* @param string $value
* @param mixed $value
* @return static
*/
public function setValue(string $value): IInputItem
public function setValue($value): IInputItem
{
$this->value = $value;
@@ -2,44 +2,21 @@
namespace Pecee\SimpleRouter\ClassLoader;
use DI\Container;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException;
class ClassLoader implements IClassLoader
{
/**
* Dependency injection enabled
* @var bool
*/
protected $useDependencyInjection = false;
/**
* @var Container|null
*/
protected $container;
/**
* Load class
*
* @param string $class
* @return mixed
* @return object
* @throws NotFoundHttpException
*/
public function loadClass(string $class)
{
if (class_exists($class) === false) {
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404);
}
if ($this->useDependencyInjection === true) {
$container = $this->getContainer();
if ($container !== null) {
try {
return $container->get($class);
} catch (\Exception $e) {
throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
throw new ClassNotFoundHttpException(sprintf('Class "%s" does not exist', $class), 404, null, $class);
}
return new $class();
@@ -51,68 +28,10 @@ class ClassLoader implements IClassLoader
* @param Callable $closure
* @param array $parameters
* @return mixed
* @throws NotFoundHttpException
*/
public function loadClosure(Callable $closure, array $parameters)
{
if ($this->useDependencyInjection === true) {
$container = $this->getContainer();
if ($container !== null) {
try {
return $container->call($closure, $parameters);
} catch (\Exception $e) {
throw new NotFoundHttpException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
}
return \call_user_func_array($closure, $parameters);
}
/**
* Get dependency injector container.
*
* @return Container|null
*/
public function getContainer(): ?Container
{
return $this->container;
}
/**
* Set the dependency-injector container.
*
* @param Container $container
* @return ClassLoader
*/
public function setContainer(Container $container): self
{
$this->container = $container;
return $this;
}
/**
* Enable or disable dependency injection.
*
* @param bool $enabled
* @return static
*/
public function useDependencyInjection(bool $enabled): self
{
$this->useDependencyInjection = $enabled;
return $this;
}
/**
* Return true if dependency injection is enabled.
*
* @return bool
*/
public function isDependencyInjectionEnabled(): bool
{
return $this->useDependencyInjection;
}
}
@@ -5,8 +5,20 @@ namespace Pecee\SimpleRouter\ClassLoader;
interface IClassLoader
{
/**
* Called when loading class
* @param string $class
* @return object
*/
public function loadClass(string $class);
/**
* Called when loading method
*
* @param callable $closure
* @param array $parameters
* @return mixed
*/
public function loadClosure(Callable $closure, array $parameters);
}
@@ -0,0 +1,38 @@
<?php
namespace Pecee\SimpleRouter\Exceptions;
use Throwable;
class ClassNotFoundHttpException extends NotFoundHttpException
{
protected $class;
protected $method;
public function __construct($message = "", $code = 0, Throwable $previous = null, string $class, ?string $method = null)
{
parent::__construct($message, $code, $previous);
$this->class = $class;
$this->method = $method;
}
/**
* Get class name
* @return string
*/
public function getClass(): string
{
return $this->class;
}
/**
* Get method
* @return string|null
*/
public function getMethod(): ?string
{
return $this->method;
}
}
@@ -143,7 +143,7 @@ class EventHandler implements IEventHandler
* Get events.
*
* @param string|null $name Filter events by name.
* @param array ...$names Add multiple names...
* @param array|string ...$names Add multiple names...
* @return array
*/
public function getEvents(?string $name, ...$names): array
+3 -3
View File
@@ -4,6 +4,7 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Router;
@@ -77,7 +78,6 @@ abstract class Route implements IRoute
$router->debug('Executing callback');
/* When the callback is a function */
return $router->getClassLoader()->loadClosure($callback, $parameters);
}
@@ -95,7 +95,7 @@ abstract class Route implements IRoute
}
if (method_exists($class, $method) === false) {
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
throw new ClassNotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404, null, $className, $method);
}
$router->debug('Executing callback');
@@ -250,7 +250,7 @@ abstract class Route implements IRoute
/**
* Set callback
*
* @param string|array\Closure $callback
* @param string|array|\Closure $callback
* @return static
*/
public function setCallback($callback): IRoute
+54 -20
View File
@@ -110,6 +110,13 @@ class Router
*/
protected $classLoader;
/**
* When enabled the router will render all routes that matches.
* When disabled the router will stop execution when first route is found.
* @var bool
*/
protected $renderMultipleRoutes = true;
/**
* Router constructor.
*/
@@ -262,13 +269,20 @@ class Router
/**
* Load routes
* @throws NotFoundHttpException
* @return void
* @throws NotFoundHttpException
*/
public function loadRoutes(): void
{
$this->debug('Loading routes');
$this->fireEvents(EventHandler::EVENT_LOAD_ROUTES, [
'routes' => $this->routes,
]);
/* Loop through each route-request */
$this->processRoutes($this->routes);
$this->fireEvents(EventHandler::EVENT_BOOT, [
'bootmanagers' => $this->bootManagers,
]);
@@ -291,13 +305,6 @@ class Router
$this->debug('Finished rendering bootmanager "%s"', $className);
}
$this->fireEvents(EventHandler::EVENT_LOAD_ROUTES, [
'routes' => $this->routes,
]);
/* Loop through each route-request */
$this->processRoutes($this->routes);
$this->debug('Finished loading routes');
}
@@ -306,7 +313,7 @@ class Router
*
* @return string|null
* @throws NotFoundHttpException
* @throws TokenMismatchException
* @throws \Pecee\Http\Middleware\Exceptions\TokenMismatchException
* @throws HttpException
* @throws \Exception
*/
@@ -350,7 +357,7 @@ class Router
{
$this->debug('Routing request');
$methodNotAllowed = false;
$methodNotAllowed = null;
try {
$url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
@@ -370,7 +377,12 @@ class Router
/* Check if request method matches */
if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$this->debug('Method "%s" not allowed', $this->request->getMethod());
$methodNotAllowed = true;
// Only set method not allowed is not already set
if ($methodNotAllowed === null) {
$methodNotAllowed = true;
}
continue;
}
@@ -394,14 +406,21 @@ class Router
'route' => $route,
]);
$output = $route->renderRoute($this->request, $this);
if ($output !== null) {
return $output;
}
$routeOutput = $route->renderRoute($this->request, $this);
$output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
if ($this->renderMultipleRoutes === true) {
if ($routeOutput !== null) {
return $routeOutput;
}
$output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
}
} else {
$output = $this->handleRouteRewrite($key, $url);
return $output ?? $routeOutput;
}
}
}
@@ -475,9 +494,9 @@ class Router
/**
* @param \Exception $e
* @throws HttpException
* @throws \Exception
* @return string|null
* @throws \Exception
* @throws HttpException
*/
protected function handleException(\Exception $e): ?string
{
@@ -907,4 +926,19 @@ class Router
return $this->debugList;
}
/**
* Changes the rendering behavior of the router.
* When enabled the router will render all routes that matches.
* When disabled the router will stop rendering at the first route that matches.
*
* @param bool $bool
* @return $this
*/
public function setRenderMultipleRoutes(bool $bool): self
{
$this->renderMultipleRoutes = $bool;
return $this;
}
}
+33 -29
View File
@@ -10,7 +10,6 @@
namespace Pecee\SimpleRouter;
use DI\Container;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
@@ -59,6 +58,11 @@ class SimpleRouter
*/
public static function start(): void
{
// Set default namespaces
foreach (static::router()->getRoutes() as $route) {
static::addDefaultNamespace($route);
}
echo static::router()->start();
}
@@ -307,8 +311,8 @@ class SimpleRouter
* @param string $url
* @param string|array|\Closure $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
* @see SimpleRouter::form
*/
public static function basic(string $url, $callback, array $settings = null): IRoute
{
@@ -322,14 +326,14 @@ class SimpleRouter
* @param string $url
* @param string|array|\Closure $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
* @see SimpleRouter::form
*/
public static function form(string $url, $callback, array $settings = null): IRoute
{
return static::match([
Request::REQUEST_TYPE_GET,
Request::REQUEST_TYPE_POST
Request::REQUEST_TYPE_POST,
], $url, $callback, $settings);
}
@@ -346,7 +350,6 @@ class SimpleRouter
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
$route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -366,7 +369,6 @@ class SimpleRouter
public static function all(string $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -386,7 +388,6 @@ class SimpleRouter
public static function controller(string $url, string $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -406,7 +407,6 @@ class SimpleRouter
public static function resource(string $url, string $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route);
if ($settings !== null) {
$route->setSettings($settings);
@@ -511,39 +511,43 @@ class SimpleRouter
{
if (static::$defaultNamespace !== null) {
$callback = $route->getCallback();
$ns = static::$defaultNamespace;
$namespace = $route->getNamespace();
/* Only add default namespace on relative callbacks */
if ($callback === null || (\is_string($callback) === true && $callback[0] !== '\\')) {
$namespace = static::$defaultNamespace;
$currentNamespace = $route->getNamespace();
if ($currentNamespace !== null) {
$namespace .= '\\' . $currentNamespace;
if ($namespace !== null) {
// Don't overwrite namespaces that starts with \
if ($namespace[0] !== '\\') {
$ns .= '\\' . $namespace;
} else {
$ns = $namespace;
}
$route->setDefaultNamespace($namespace);
}
$route->setNamespace($ns);
}
return $route;
}
/**
* Enable or disable dependency injection
* Changes the rendering behavior of the router.
* When enabled the router will render all routes that matches.
* When disabled the router will stop rendering at the first route that matches.
*
* @param Container $container
* @return IClassLoader
* @param bool $bool
*/
public static function enableDependencyInjection(Container $container): IClassLoader
public static function enableMultiRouteRendering(bool $bool): void
{
return static::router()
->getClassLoader()
->useDependencyInjection(true)
->setContainer($container);
static::router()->setRenderMultipleRoutes($bool);
}
/**
* Set custom class-loader class used.
* @param IClassLoader $classLoader
*/
public static function setCustomClassLoader(IClassLoader $classLoader): void
{
static::router()->setClassLoader($classLoader);
}
/**
@@ -0,0 +1,49 @@
<?php
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Dummy/Managers/TestBootManager.php';
require_once 'Dummy/Managers/FindUrlBootManager.php';
class BootManagerTest extends \PHPUnit\Framework\TestCase
{
public function testBootManagerRoutes()
{
$result = false;
TestRouter::get('/', function () use (&$result) {
$result = true;
});
TestRouter::get('/about', 'DummyController@method2');
TestRouter::get('/contact', 'DummyController@method3');
// Add boot-manager
TestRouter::addBootManager(new TestBootManager([
'/con' => '/about',
'/contact' => '/',
]));
TestRouter::debug('/contact');
$this->assertTrue($result);
}
public function testFindUrlFromBootManager()
{
TestRouter::get('/', 'DummyController@method1');
TestRouter::get('/about', 'DummyController@method2')->name('about');
TestRouter::get('/contact', 'DummyController@method3')->name('contact');
$result = false;
// Add boot-manager
TestRouter::addBootManager(new FindUrlBootManager($result));
TestRouter::debug('/');
$this->assertTrue($result);
}
}
@@ -0,0 +1,30 @@
<?php
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/ClassLoader/CustomClassLoader.php';
class ClassLoaderTest extends \PHPUnit\Framework\TestCase
{
public function testCustomClassLoader()
{
$result = false;
TestRouter::setCustomClassLoader(new CustomClassLoader());
TestRouter::get('/', 'NonExistingClass@method3');
TestRouter::get('/test-closure', function($status) use(&$result) {
$result = $status;
});
$classLoaderClass = TestRouter::debugOutput('/', 'get', false);
TestRouter::debugOutput('/test-closure');
$this->assertEquals('method3', $classLoaderClass);
$this->assertTrue($result);
TestRouter::router()->reset();
}
}
@@ -1,53 +0,0 @@
<?php
require_once 'Dummy/DummyMiddleware.php';
class DependencyInjectionTest extends \PHPUnit\Framework\TestCase
{
public function testDependencyInjectionDevelopment()
{
$builder = new \DI\ContainerBuilder();
$container = $builder
->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);
}
}
@@ -0,0 +1,14 @@
<?php
class CustomClassLoader implements \Pecee\SimpleRouter\ClassLoader\IClassLoader
{
public function loadClass(string $class)
{
return new DummyController();
}
public function loadClosure(callable $closure, array $parameters)
{
return \call_user_func_array($closure, ['result' => true]);
}
}
@@ -16,6 +16,11 @@ class DummyController
public function method2()
{
}
public function method3()
{
return 'method3';
}
public function param($params = null)
@@ -0,0 +1,26 @@
<?php
class FindUrlBootManager implements \Pecee\SimpleRouter\IRouterBootManager
{
protected $result;
public function __construct(&$result)
{
$this->result = &$result;
}
/**
* Called when router loads it's routes
*
* @param \Pecee\SimpleRouter\Router $router
* @param \Pecee\Http\Request $request
*/
public function boot(\Pecee\SimpleRouter\Router $router, \Pecee\Http\Request $request): void
{
$contact = $router->findRoute('contact');
if($contact !== null) {
$this->result = true;
}
}
}
@@ -3,13 +3,11 @@
class TestBootManager implements \Pecee\SimpleRouter\IRouterBootManager
{
protected $routes;
protected $aliasUrl;
protected $rewrite;
public function __construct(array $routes, string $aliasUrl)
public function __construct(array $rewrite)
{
$this->routes = $routes;
$this->aliasUrl = $aliasUrl;
$this->rewrite = $rewrite;
}
/**
@@ -20,11 +18,11 @@ class TestBootManager implements \Pecee\SimpleRouter\IRouterBootManager
*/
public function boot(\Pecee\SimpleRouter\Router $router, \Pecee\Http\Request $request): void
{
foreach ($this->routes as $url) {
foreach ($this->rewrite as $url => $rewrite) {
// If the current url matches the rewrite url, we use our custom route
if ($request->getUrl()->contains($url) === true) {
$request->setRewriteUrl($this->aliasUrl);
$request->setRewriteUrl($rewrite);
}
}
@@ -50,8 +50,8 @@ class EventHandlerTest extends \PHPUnit\Framework\TestCase
// Add boot-manager
TestRouter::addBootManager(new TestBootManager([
'/test',
], '/'));
'/test' => '/',
]));
// Start router
TestRouter::debug('/non-existing');
@@ -61,7 +61,6 @@ class EventHandlerTest extends \PHPUnit\Framework\TestCase
public function testAllEvent()
{
$status = false;
$eventHandler = new EventHandler();
@@ -6,7 +6,7 @@ require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Dummy/Middleware/RewriteMiddleware.php';
class RouteRewriteTest extends \PHPUnit\Framework\TestCase
class RouterRewriteTest extends \PHPUnit\Framework\TestCase
{
/**
@@ -210,4 +210,15 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
$this->assertTrue(true);
}
public function testSameRoutes()
{
TestRouter::get('/recipe', 'DummyController@method1')->name('add');
TestRouter::post('/recipe', 'DummyController@method2')->name('edit');
TestRouter::debugNoReset('/recipe', 'post');
TestRouter::debug('/recipe', 'get');
$this->assertTrue(true);
}
}
+90 -2
View File
@@ -11,7 +11,7 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
{
TestRouter::get('/', 'DummyController@method1');
TestRouter::get('/page/{id?}', 'DummyController@method1');
TestRouter::get('/test-output', function() {
TestRouter::get('/test-output', function () {
return 'return value';
});
@@ -175,7 +175,7 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
{
TestRouter::request()->setHost('google.com');
TestRouter::get('/admin/', function() {
TestRouter::get('/admin/', function () {
return 'match';
})->setMatch('/^\/admin\/?(.*)/i');
@@ -183,4 +183,92 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('match', $output);
}
public function testRenderMultipleRoutesDisabled()
{
TestRouter::router()->setRenderMultipleRoutes(false);
$result = false;
TestRouter::get('/', function () use (&$result) {
$result = true;
});
TestRouter::get('/', function () use (&$result) {
$result = false;
});
TestRouter::debug('/');
$this->assertTrue($result);
}
public function testRenderMultipleRoutesEnabled()
{
TestRouter::router()->setRenderMultipleRoutes(true);
$result = [];
TestRouter::get('/', function () use (&$result) {
$result[] = 'route1';
});
TestRouter::get('/', function () use (&$result) {
$result[] = 'route2';
});
TestRouter::debug('/');
$this->assertCount(2, $result);
}
public function testDefaultNamespace()
{
TestRouter::setDefaultNamespace('\\Default\\Namespace');
TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
TestRouter::group([
'namespace' => 'Appended\Namespace',
'prefix' => '/horses',
], function () {
TestRouter::get('/', 'DummyController@method1');
TestRouter::group([
'namespace' => '\\New\\Namespace',
'prefix' => '/race',
], function () {
TestRouter::get('/', 'DummyController@method1');
});
});
// Test appended namespace
$class = null;
try {
TestRouter::debugNoReset('/horses/');
} catch (\Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException $e) {
$class = $e->getClass();
}
$this->assertEquals('\\Default\\Namespace\\Appended\Namespace\\DummyController', $class);
// Test overwritten namespace
$class = null;
try {
TestRouter::debugNoReset('/horses/race');
} catch (\Pecee\SimpleRouter\Exceptions\ClassNotFoundHttpException $e) {
$class = $e->getClass();
}
$this->assertEquals('\\New\\Namespace\\DummyController', $class);
TestRouter::router()->reset();
}
}