Development

- Fixed issue #227 causing custom resource-routes not to be loaded after latest update.
- Optimized `RouteResource` class.
- Renamed `IRestController` to `IResourceController`.
- Added unit-tests for RouterResource.
- Simplified unit-tests with the `TestRouter` custom router class.
This commit is contained in:
Simon Sessingø
2017-03-05 17:09:46 +01:00
parent 8c5d8c2dc9
commit ff3f1bdcdd
16 changed files with 386 additions and 243 deletions
@@ -1,7 +1,7 @@
<?php <?php
namespace Pecee\Controllers; namespace Pecee\Controllers;
interface IRestController interface IResourceController
{ {
/** /**
+11 -10
View File
@@ -84,41 +84,42 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/* Match global regular-expression for route */ /* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url); $regexMatch = $this->matchRegex($request, $url);
if ($regexMatch === false || stripos($url, $this->url) !== 0 || strtolower($url) !== strtolower($this->url)) { if ($regexMatch === false) {
return false; return false;
} }
$route = rtrim($this->url, '/') . '/{id?}/{action?}'; $route = rtrim($this->url, '/') . '/{id?}/{action?}';
$parameters = $this->parseParameters($route, $url); $this->parameters = $this->parseParameters($route, $url);
if ($parameters === null) { if ($this->parameters === null) {
return false; return false;
} }
$this->parameters = (array)$parameters; $action = strtolower(trim($this->parameters['action']));
$id = $this->parameters['id'];
$action = isset($this->parameters['action']) ? $this->parameters['action'] : null; // Remove action parameter
unset($this->parameters['action']); unset($this->parameters['action']);
$method = $request->getMethod(); $method = $request->getMethod();
// Delete // Delete
if ($method === static::REQUEST_TYPE_DELETE && isset($this->parameters['id'])) { if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
return $this->call($this->methodNames['destroy']); return $this->call($this->methodNames['destroy']);
} }
// Update // Update
if (isset($this->parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false)) { if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
return $this->call($this->methodNames['update']); return $this->call($this->methodNames['update']);
} }
// Edit // Edit
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id']) && strtolower($action) === 'edit') { if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
return $this->call($this->methodNames['edit']); return $this->call($this->methodNames['edit']);
} }
// Create // Create
if ($method === static::REQUEST_TYPE_GET && strtolower($action) === 'create') { if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
return $this->call($this->methodNames['create']); return $this->call($this->methodNames['create']);
} }
@@ -128,7 +129,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
} }
// Show // Show
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id'])) { if ($method === static::REQUEST_TYPE_GET && $id !== null) {
return $this->call($this->methodNames['show']); return $this->call($this->methodNames['show']);
} }
+8 -13
View File
@@ -2,24 +2,19 @@
class DummyController class DummyController
{ {
public function start() public function method1()
{ {
echo static::class . '@' . 'start() OK';
} }
public function method2()
{
}
public function param($params = null) public function param($params = null)
{ {
$params = func_get_args(); echo join(', ', func_get_args());
echo 'Params: ' . join(', ', $params);
}
public function notFound()
{
echo 'not found';
}
public function silent() {
} }
} }
@@ -0,0 +1,18 @@
<?php
class ResponseException extends \Exception
{
protected $response;
public function __construct($response)
{
$this->response = $response;
parent::__construct('', 0);
}
public function getResponse()
{
return $this->response;
}
}
@@ -1,10 +1,11 @@
<?php <?php
class TestExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error)
{ {
echo 'ExceptionHandler 1 loaded' . chr(10); global $stack;
$stack[] = static::class;
$request->setUri('/'); $request->setUri('/');
return $request; return $request;
@@ -1,10 +1,11 @@
<?php <?php
class TestExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error)
{ {
echo 'ExceptionHandler 2 loaded' . chr(10); global $stack;
$stack[] = static::class;
$request->setUri('/'); $request->setUri('/');
return $request; return $request;
@@ -0,0 +1,13 @@
<?php
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
throw new ResponseException('ExceptionHandler loaded');
}
}
@@ -1,12 +0,0 @@
<?php
class TestExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
echo 'ExceptionHandler 3 loaded' . chr(10);
throw new ExceptionHandlerException('All good!', 666);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
class ResourceController implements \Pecee\Controllers\IResourceController
{
public function index()
{
echo 'index';
}
public function show($id)
{
echo 'show ' . $id;
}
public function store()
{
echo 'store';
}
public function create()
{
echo 'create';
}
public function edit($id)
{
echo 'edit ' . $id;
}
public function update($id)
{
echo 'update ' . $id;
}
public function destroy($id)
{
echo 'destroy ' . $id;
}
}
+26 -38
View File
@@ -2,8 +2,7 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
class GroupTest extends PHPUnit_Framework_TestCase class GroupTest extends PHPUnit_Framework_TestCase
{ {
@@ -13,82 +12,71 @@ class GroupTest extends PHPUnit_Framework_TestCase
{ {
$this->result = false; $this->result = false;
SimpleRouter::group(['prefix' => '/group'], function () { TestRouter::group(['prefix' => '/group'], function () {
$this->result = true; $this->result = true;
}); });
try { try {
SimpleRouter::start(); TestRouter::debug('/', 'get');
} catch (Exception $e) { } catch(\Exception $e) {
// ignore RouteNotFound exception
}
}
$this->assertTrue($this->result); $this->assertTrue($this->result);
} }
public function testNestedGroup() public function testNestedGroup()
{ {
SimpleRouter::router()->reset(); TestRouter::group(['prefix' => '/api'], function () {
SimpleRouter::request()->setUri('/api/v1/test');
SimpleRouter::request()->setMethod('get');
SimpleRouter::group(['prefix' => '/api'], function () { TestRouter::group(['prefix' => '/v1'], function () {
TestRouter::get('/test', 'DummyController@method1');
SimpleRouter::group(['prefix' => '/v1'], function () {
SimpleRouter::get('/test', 'DummyController@start');
}); });
}); });
SimpleRouter::start(); TestRouter::debug('/api/v1/test', 'get');
} }
public function testManyRoutes() public function testMultipleRoutes()
{ {
SimpleRouter::router()->reset(); TestRouter::group(['prefix' => '/api'], function () {
SimpleRouter::request()->setUri('/my/match');
SimpleRouter::request()->setMethod('get');
SimpleRouter::group(['prefix' => '/api'], function () { TestRouter::group(['prefix' => '/v1'], function () {
TestRouter::get('/test', 'DummyController@method1');
SimpleRouter::group(['prefix' => '/v1'], function () {
SimpleRouter::get('/test', 'DummyController@start');
}); });
}); });
SimpleRouter::get('/my/match', 'DummyController@start'); TestRouter::get('/my/match', 'DummyController@method1');
SimpleRouter::group(['prefix' => '/service'], function () { TestRouter::group(['prefix' => '/service'], function () {
SimpleRouter::group(['prefix' => '/v1'], function () { TestRouter::group(['prefix' => '/v1'], function () {
SimpleRouter::get('/no-match', 'DummyController@start'); TestRouter::get('/no-match', 'DummyController@method1');
}); });
}); });
SimpleRouter::start(); TestRouter::debug('/my/match', 'get');
} }
public function testUrls() public function testUrls()
{ {
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/fancy/url/1');
SimpleRouter::request()->setMethod('get');
// Test array name // Test array name
SimpleRouter::get('/my/fancy/url/1', 'DummyController@start', ['as' => 'fancy1']); TestRouter::get('/my/fancy/url/1', 'DummyController@method1', ['as' => 'fancy1']);
// Test method name // Test method name
SimpleRouter::get('/my/fancy/url/2', 'DummyController@start')->setName('fancy2'); TestRouter::get('/my/fancy/url/2', 'DummyController@method1')->setName('fancy2');
SimpleRouter::start(); TestRouter::debugNoReset('/my/fancy/url/1');
$this->assertEquals('/my/fancy/url/1/', SimpleRouter::getUrl('fancy1')); $this->assertEquals('/my/fancy/url/1/', TestRouter::getUrl('fancy1'));
$this->assertEquals('/my/fancy/url/2/', SimpleRouter::getUrl('fancy2')); $this->assertEquals('/my/fancy/url/2/', TestRouter::getUrl('fancy2'));
TestRouter::router()->reset();
} }
+41
View File
@@ -0,0 +1,41 @@
<?php
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
{
public static function debugNoReset($testUri, $testMethod = 'get')
{
static::request()->setUri($testUri);
static::request()->setMethod($testMethod);
static::start();
}
public static function debug($testUri, $testMethod = 'get')
{
try {
static::debugNoReset($testUri, $testMethod);
} catch(\Exception $e) {
static::router()->reset();
throw $e;
}
static::router()->reset();
}
public static function debugOutput($testUri, $testMethod = 'get')
{
$response = null;
// Route request
ob_start();
static::debug($testUri, $testMethod);
$response = ob_get_contents();
ob_end_clean();
// Return response
return $response;
}
}
+12 -19
View File
@@ -3,39 +3,32 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php'; require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
class MiddlewareTest extends PHPUnit_Framework_TestCase class MiddlewareTest extends PHPUnit_Framework_TestCase
{ {
public function testMiddlewareFound() public function testMiddlewareFound()
{ {
$this->setExpectedException('MiddlewareLoadedException'); $this->setExpectedException(MiddlewareLoadedException::class);
SimpleRouter::router()->reset(); TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
SimpleRouter::request()->setMethod('get'); TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
}); });
SimpleRouter::start(); TestRouter::debug('/my/test/url', 'get');
} }
public function testNestedMiddlewareLoad() public function testNestedMiddlewareDontLoad()
{ {
$this->setExpectedException('MiddlewareLoadedException');
SimpleRouter::router()->reset(); TestRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
SimpleRouter::request()->setMethod('get'); TestRouter::get('/middleware', 'DummyController@method1');
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
SimpleRouter::get('/my/test/url', 'DummyController@start');
}); });
SimpleRouter::start(); TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
} }
} }
+70
View File
@@ -0,0 +1,70 @@
<?php
require_once 'Dummy/ResourceController.php';
require_once 'Helpers/TestRouter.php';
class RouterResourceTest extends PHPUnit_Framework_TestCase
{
public function testResourceStore()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource', 'post');
$this->assertEquals('store', $response);
}
public function testResourceCreate()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/create', 'get');
$this->assertEquals('create', $response);
}
public function testResourceIndex()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource', 'get');
$this->assertEquals('index', $response);
}
public function testResourceDestroy()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38', 'delete');
$this->assertEquals('destroy 38', $response);
}
public function testResourceEdit()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38/edit', 'get');
$this->assertEquals('edit 38', $response);
}
public function testResourceUpdate()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38', 'put');
$this->assertEquals('update 38', $response);
}
public function testResourceGet()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38', 'get');
$this->assertEquals('show 38', $response);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
require_once 'Dummy/Exceptions/ResponseException.php';
require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Helpers/TestRouter.php';
class RouteRewriteTest extends PHPUnit_Framework_TestCase
{
/**
* Redirects to another route through 3 exception handlers.
*
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
* the exceptionhandler is asking the router to reload.
*
* That means that the exceptionhandler is loaded again, but this time
* the router ignores the same rewrite-route to avoid loop - loads
* the second which have same behavior and is also ignored before
* throwing the final Exception in ExceptionHandler 3.
*
* So this tests:
* 1. If ExceptionHandlers loads
* 2. If ExceptionHandlers load in the correct order
* 3. If ExceptionHandlers can rewrite the page on error
* 4. If the router can avoid redirect-loop due to developer has started loop.
* 5. And finally if we reaches the last exception-handler and that the correct
* exception-type is being thrown.
*/
public function testExceptionHandlerRewrite()
{
global $stack;
$stack = [];
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () {
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () {
TestRouter::get('/my-path', 'DummyController@method1');
});
});
try {
TestRouter::debug('/my-non-existing-path', 'get');
} catch(\ResponseException $e) {
}
$expectedStack = [
ExceptionHandlerFirst::class,
ExceptionHandlerSecond::class,
ExceptionHandlerThird::class,
];
$this->assertEquals($expectedStack, $stack);
}
}
+53 -97
View File
@@ -3,12 +3,7 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
require_once 'Dummy/Handler/TestExceptionHandlerFirst.php'; require_once 'Helpers/TestRouter.php';
require_once 'Dummy/Handler/TestExceptionHandlerSecond.php';
require_once 'Dummy/Handler/TestExceptionHandlerThird.php';
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException as NotFoundHttpException;
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
class RouterRouteTest extends PHPUnit_Framework_TestCase class RouterRouteTest extends PHPUnit_Framework_TestCase
{ {
@@ -16,113 +11,57 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
public function testMultiParam() public function testMultiParam()
{ {
SimpleRouter::router()->reset(); TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) {
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test-param1-param2');
SimpleRouter::get('/test-{param1}-{param2}', function($param1, $param2) { if ($param1 === 'param1' && $param2 === 'param2') {
if($param1 === 'param1' && $param2 === 'param2') {
$this->result = true; $this->result = true;
} }
}); });
SimpleRouter::start(); TestRouter::debug('/test-param1-param2', 'get');
$this->assertTrue($this->result); $this->assertTrue($this->result);
} }
/**
* Redirects to another route through 3 exception handlers.
*
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
* the exceptionhandler is asking the router to reload.
*
* That means that the exceptionhandler is loaded again, but this time
* the router ignores the same rewrite-route to avoid loop - loads
* the second which have same behavior and is also ignored before
* throwing the final Exception in ExceptionHandler 3.
*
* So this tests:
* 1. If ExceptionHandlers loads
* 2. If ExceptionHandlers load in the correct order
* 3. If ExceptionHandlers can rewrite the page on error
* 4. If the router can avoid redirect-loop due to developer has started loop.
* 5. And finally if we reaches the last exception-handler and that the correct
* exception-type is being thrown.
*/
public function testNotFound() public function testNotFound()
{ {
$this->setExpectedException('ExceptionHandlerException'); $this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1');
SimpleRouter::router()->reset(); TestRouter::debug('/test-param1-param2', 'post');
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test-param1-param2');
SimpleRouter::group(['exceptionHandler' => ['TestExceptionHandlerFirst', 'TestExceptionHandlerSecond']], function () {
SimpleRouter::group(['exceptionHandler' => 'TestExceptionHandlerThird'], function () {
SimpleRouter::get('/non-existing-path', 'DummyController@start');
});
});
SimpleRouter::start();
} }
public function testGet() public function testGet()
{ {
SimpleRouter::router()->reset(); TestRouter::get('/my/test/url', 'DummyController@method1');
SimpleRouter::request()->setUri('/my/test/url'); TestRouter::debug('/my/test/url', 'get');
SimpleRouter::request()->setMethod('get');
SimpleRouter::get('/my/test/url', 'DummyController@start');
SimpleRouter::start();
} }
public function testPost() public function testPost()
{ {
SimpleRouter::router()->reset(); TestRouter::post('/my/test/url', 'DummyController@method1');
SimpleRouter::request()->setUri('/my/test/url'); TestRouter::debug('/my/test/url', 'post');
SimpleRouter::request()->setMethod('post');
SimpleRouter::post('/my/test/url', 'DummyController@start');
SimpleRouter::start();
} }
public function testPut() public function testPut()
{ {
SimpleRouter::router()->reset(); TestRouter::put('/my/test/url', 'DummyController@method1');
SimpleRouter::request()->setUri('/my/test/url'); TestRouter::debug('/my/test/url', 'put');
SimpleRouter::request()->setMethod('put');
SimpleRouter::put('/my/test/url', 'DummyController@start');
SimpleRouter::start();
} }
public function testDelete() public function testDelete()
{ {
SimpleRouter::router()->reset(); TestRouter::delete('/my/test/url', 'DummyController@method1');
SimpleRouter::request()->setUri('/my/test/url'); TestRouter::debug('/my/test/url', 'delete');
SimpleRouter::request()->setMethod('delete');
SimpleRouter::delete('/my/test/url', 'DummyController@start');
SimpleRouter::start();
} }
public function testMethodNotAllowed() public function testMethodNotAllowed()
{ {
SimpleRouter::router()->reset(); TestRouter::get('/my/test/url', 'DummyController@method1');
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::request()->setMethod('post');
SimpleRouter::get('/my/test/url', 'DummyController@start');
try { try {
SimpleRouter::start(); TestRouter::debug('/my/test/url', 'post');
} catch (\Exception $e) { } catch (\Exception $e) {
$this->assertEquals(403, $e->getCode()); $this->assertEquals(403, $e->getCode());
} }
@@ -130,43 +69,60 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
public function testSimpleParam() public function testSimpleParam()
{ {
SimpleRouter::router()->reset(); TestRouter::get('/test-{param1}', 'DummyController@param');
SimpleRouter::request()->setMethod('get'); $response = TestRouter::debugOutput('/test-param1', 'get');
SimpleRouter::request()->setUri('/test-param1');
SimpleRouter::get('/test-{param1}', 'DummyController@param'); $this->assertEquals('param1', $response);
SimpleRouter::start();
} }
public function testPathParamRegex() public function testPathParamRegex()
{ {
SimpleRouter::router()->reset(); TestRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
SimpleRouter::request()->setMethod('get'); $response = TestRouter::debugOutput('/test/path/123123', 'get');
SimpleRouter::request()->setUri('/test/path/123123');
SimpleRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]); $this->assertEquals('123123', $response);
SimpleRouter::start();
} }
public function testDomainRoute() public function testDomainAllowedRoute()
{ {
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test');
SimpleRouter::request()->setHost('hello.world.com');
$this->result = false; $this->result = false;
SimpleRouter::group(['domain' => '{subdomain}.world.com'], function () { TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
SimpleRouter::get('/test', function ($subdomain = null) { TestRouter::get('/test', function ($subdomain = null) {
$this->result = ($subdomain === 'hello'); $this->result = ($subdomain === 'hello');
}); });
}); });
SimpleRouter::start(); TestRouter::request()->setHost('hello.world.com');
TestRouter::debug('/test', 'get');
$this->assertTrue($this->result); $this->assertTrue($this->result);
} }
public function testDomainNotAllowedRoute()
{
$this->result = false;
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
TestRouter::get('/test', function ($subdomain = null) {
$this->result = ($subdomain === 'hello');
});
});
TestRouter::request()->setHost('other.world.com');
TestRouter::debug('/test', 'get');
$this->assertFalse($this->result);
}
public function testRegEx()
{
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
TestRouter::debug('/my/custom-path', 'get');
}
} }
+28 -49
View File
@@ -3,111 +3,90 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php'; require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
class RouterUrlTest extends PHPUnit_Framework_TestCase class RouterUrlTest extends PHPUnit_Framework_TestCase
{ {
protected $result = false;
protected function getUrl($name = null, $parameters = null, array $getParams = [])
{
return SimpleRouter::getUrl($name, $parameters, $getParams);
}
public function testUrls() public function testUrls()
{ {
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/');
// Match normal route on alias // Match normal route on alias
SimpleRouter::get('/', 'DummyController@silent', ['as' => 'home']); TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
SimpleRouter::get('/about', 'DummyController@about'); TestRouter::get('/about', 'DummyController@about');
SimpleRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () { TestRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
// Match route with prefix on alias // Match route with prefix on alias
SimpleRouter::get('/{id?}', 'DummyController@start', ['as' => 'home']); TestRouter::get('/{id?}', 'DummyController@method2', ['as' => 'home']);
// Match controller with prefix and alias // Match controller with prefix and alias
SimpleRouter::controller('/users', 'DummyController', ['as' => 'users']); TestRouter::controller('/users', 'DummyController', ['as' => 'users']);
// Match controller with prefix and NO alias // Match controller with prefix and NO alias
SimpleRouter::controller('/pages', 'DummyController'); TestRouter::controller('/pages', 'DummyController');
}); });
SimpleRouter::group(['prefix' => 'api', 'as' => 'api'], function () { TestRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
// Match resource controller // Match resource controller
SimpleRouter::resource('phones', 'DummyController'); TestRouter::resource('phones', 'DummyController');
}); });
SimpleRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]); TestRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
// Match controller with no prefix and no alias // Match controller with no prefix and no alias
SimpleRouter::controller('/cats', 'CatsController'); TestRouter::controller('/cats', 'CatsController');
// Pretend to load page // Pretend to load page
SimpleRouter::start(); TestRouter::debugNoReset('/', 'get');
$this->assertEquals('/gadgets/iphoneinfo/', $this->getUrl('gadgets.iphone')); $this->assertEquals('/gadgets/iphoneinfo/', TestRouter::getUrl('gadgets.iphone'));
$this->assertEquals('/api/phones/create/', $this->getUrl('api.phones.create')); $this->assertEquals('/api/phones/create/', TestRouter::getUrl('api.phones.create'));
// Should match / // Should match /
$this->assertEquals('/', $this->getUrl('home')); $this->assertEquals('/', TestRouter::getUrl('home'));
// Should match /about/ // Should match /about/
$this->assertEquals('/about/', $this->getUrl('DummyController@about')); $this->assertEquals('/about/', TestRouter::getUrl('DummyController@about'));
// Should match /admin/ // Should match /admin/
$this->assertEquals('/admin/', $this->getUrl('DummyController@start')); $this->assertEquals('/admin/', TestRouter::getUrl('DummyController@method2'));
// Should match /admin/ // Should match /admin/
$this->assertEquals('/admin/', $this->getUrl('admin.home')); $this->assertEquals('/admin/', TestRouter::getUrl('admin.home'));
// Should match /admin/2/ // Should match /admin/2/
$this->assertEquals('/admin/2/', $this->getUrl('admin.home', ['id' => 2])); $this->assertEquals('/admin/2/', TestRouter::getUrl('admin.home', ['id' => 2]));
// Should match /admin/users/ // Should match /admin/users/
$this->assertEquals('/admin/users/', $this->getUrl('admin.users')); $this->assertEquals('/admin/users/', TestRouter::getUrl('admin.users'));
// Should match /admin/users/home/ // Should match /admin/users/home/
$this->assertEquals('/admin/users/home/', $this->getUrl('admin.users@home')); $this->assertEquals('/admin/users/home/', TestRouter::getUrl('admin.users@home'));
// Should match /cats/ // Should match /cats/
$this->assertEquals('/cats/', $this->getUrl('CatsController')); $this->assertEquals('/cats/', TestRouter::getUrl('CatsController'));
// Should match /cats/view/ // Should match /cats/view/
$this->assertEquals('/cats/view/', $this->getUrl('CatsController', 'view')); $this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', 'view'));
// Should match /cats/view/ // Should match /cats/view/
//$this->assertEquals('/cats/view/', $this->getUrl('CatsController', ['view'])); //$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', ['view']));
// Should match /cats/view/666 // Should match /cats/view/666
$this->assertEquals('/cats/view/666/', $this->getUrl('CatsController@getView', ['666'])); $this->assertEquals('/cats/view/666/', TestRouter::getUrl('CatsController@getView', ['666']));
// Should match /funny/man/ // Should match /funny/man/
$this->assertEquals('/funny/man/', $this->getUrl('/funny/man')); $this->assertEquals('/funny/man/', TestRouter::getUrl('/funny/man'));
// Should match /?jackdaniels=true&cola=yeah // Should match /?jackdaniels=true&cola=yeah
$this->assertEquals('/?jackdaniels=true&cola=yeah', $this->getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah'])); $this->assertEquals('/?jackdaniels=true&cola=yeah', TestRouter::getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
} TestRouter::router()->reset();
public function testRegEx()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/my/custom-path');
SimpleRouter::get('/my/{path}', 'DummyController@start')->where(['path' => '[a-zA-Z\-]+']);
SimpleRouter::start();
} }