84 lines
2.7 KiB
PHP
84 lines
2.7 KiB
PHP
<?php declare(strict_types=1);
|
|
|
|
use PHPUnit\Framework\TestCase;
|
|
use Sharkk\Router\SegmentRouter;
|
|
|
|
final class SegmentRouterTest extends TestCase
|
|
{
|
|
private SegmentRouter $router;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->router = new SegmentRouter();
|
|
}
|
|
|
|
public function testAddAndLookupRoute(): void
|
|
{
|
|
$routes = [];
|
|
SegmentRouter::add($routes, 'GET', '/blog/:id', function($id) {
|
|
return "Blog post $id";
|
|
});
|
|
|
|
$result = SegmentRouter::lookup($routes, 'GET', '/blog/123');
|
|
$this->assertEquals(200, $result['code']);
|
|
$this->assertIsCallable($result['handler']);
|
|
$this->assertEquals(['123'], $result['params']);
|
|
$this->assertEquals("Blog post 123", $result['handler'](...$result['params']));
|
|
}
|
|
|
|
public function testLookupNotFound(): void
|
|
{
|
|
$routes = [];
|
|
SegmentRouter::add($routes, 'GET', '/blog/:id', function($id) {
|
|
return "Blog post $id";
|
|
});
|
|
|
|
$result = SegmentRouter::lookup($routes, 'GET', '/nonexistent');
|
|
$this->assertEquals(404, $result['code']);
|
|
$this->assertNull($result['handler']);
|
|
$this->assertEmpty($result['params']);
|
|
}
|
|
|
|
public function testMethodNotAllowed(): void
|
|
{
|
|
$routes = [];
|
|
SegmentRouter::add($routes, 'GET', '/blog/:id', function($id) {
|
|
return "Blog post $id";
|
|
});
|
|
|
|
$result = SegmentRouter::lookup($routes, 'POST', '/blog/123');
|
|
$this->assertEquals(405, $result['code']);
|
|
$this->assertNull($result['handler']);
|
|
$this->assertEmpty($result['params']);
|
|
}
|
|
|
|
public function testClearRoutes(): void
|
|
{
|
|
$routes = [];
|
|
SegmentRouter::add($routes, 'GET', '/blog/:id', function($id) {
|
|
return "Blog post $id";
|
|
});
|
|
|
|
SegmentRouter::clear($routes);
|
|
$this->assertEmpty($routes);
|
|
}
|
|
|
|
public function testAddMultipleMethods(): void
|
|
{
|
|
$routes = [];
|
|
SegmentRouter::add($routes, 'GET', '/blog/:id', function($id) {
|
|
return "GET Blog post $id";
|
|
});
|
|
SegmentRouter::add($routes, 'POST', '/blog/:id', function($id) {
|
|
return "POST Blog post $id";
|
|
});
|
|
|
|
$resultGet = SegmentRouter::lookup($routes, 'GET', '/blog/123');
|
|
$this->assertEquals(200, $resultGet['code']);
|
|
$this->assertEquals("GET Blog post 123", $resultGet['handler'](...$resultGet['params']));
|
|
|
|
$resultPost = SegmentRouter::lookup($routes, 'POST', '/blog/123');
|
|
$this->assertEquals(200, $resultPost['code']);
|
|
$this->assertEquals("POST Blog post 123", $resultPost['handler'](...$resultPost['params']));
|
|
}
|
|
} |