Skip to content

Commit

Permalink
Add an exact path route (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
bajb committed Feb 6, 2024
1 parent 00d9f8d commit 1e0414e
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 1 deletion.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
}
],
"require": {
"php": ">=7.2",
"php": ">=8.0",
"packaged/context": "~1.0",
"packaged/helpers": "~2.0"
},
Expand Down
36 changes: 36 additions & 0 deletions src/Routes/ExactPathRoute.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Packaged\Routing\Routes;

use Packaged\Context\Context;
use Packaged\Routing\Handler\Handler;
use Packaged\Routing\Route;

class ExactPathRoute extends Route
{
protected array $_paths = [];

/**
* @param string $exactPath
* @param Handler|string|callable $handler
*
* @return $this
*/
public function addPath(string $exactPath, Handler|string|callable $handler): static
{
$this->_paths[$exactPath] = $handler;
return $this;
}

public function match(Context $context): bool
{
$path = $context->request()->path();
if(isset($this->_paths[$path]))
{
$this->setHandler($this->_paths[$path]);
return true;
}

return false;
}
}
53 changes: 53 additions & 0 deletions tests/Routes/ExactPathRouteTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Packaged\Tests\Routing\Routes;

use Packaged\Context\Context;
use Packaged\Http\Request;
use Packaged\Routing\Routes\ExactPathRoute;
use PHPUnit\Framework\TestCase;

class ExactPathRouteTest extends TestCase
{
public function testUnmatchedPath()
{
$ctx = new Context(Request::create('http://www.google.com/a/b/c/?d=e&f=g'));

$route = new ExactPathRoute();
$route->addPath('/test', 'test');
static::assertFalse($route->match($ctx));
}

public function matchPathProvider()
{
return [
['/test', 'testHandle'],
['/test/', 'testHandle'],
['/test?query=string', 'testHandle'],
['/test/?query=string', 'testHandle'],
['/test/?query=string&another=param', 'testHandle'],
['/secondary', 'handleTwo'],
['/random', 'randomHandle'],
];
}

/**
* @param $url
* @param $handler
*
* @dataProvider matchPathProvider
* @return void
*/
public function testMatchedPath($url, $handler)
{
$ctx = new Context(Request::create($url));

$route = new ExactPathRoute();
$route->addPath('/test', 'testHandle');
$route->addPath('/test/', 'testHandle');
$route->addPath('/secondary', 'handleTwo');
$route->addPath('/random', 'randomHandle');
static::assertTrue($route->match($ctx));
static::assertEquals($handler, $route->getHandler());
}
}

0 comments on commit 1e0414e

Please sign in to comment.