Skip to content

Commit

Permalink
feat: controllers can have optional params
Browse files Browse the repository at this point in the history
  • Loading branch information
ipranjal committed Oct 18, 2024
1 parent 6b84cd3 commit 99921ee
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 8 deletions.
11 changes: 8 additions & 3 deletions src/RouterEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,14 @@ private function getArguments(string $controller, string $method): bool|array
}
// Check weather arguments are passed else throw a 404 error
$classMethod = new \ReflectionMethod($controllerObj, $method);

// Optional parameter introduced in version 3.0.2
if (count($arguments) < count($classMethod->getParameters())) {
$params = $classMethod->getParameters();
// Remove params if it allows null
foreach ($params as $key => $param) {
if ($param->isOptional()) {
unset($params[$key]);
}
}
if (count($arguments) < count($params)) {
$this->debug('Not enough arguments given to the method');

return false;
Expand Down
15 changes: 15 additions & 0 deletions tests/Demo/Param.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php
namespace Tests\Demo;
class Param
{

public function allIndex($id=null)
{
return "Index Test";
}

public function getTest($id=null)
{
return "Test Test";
}
}
11 changes: 6 additions & 5 deletions tests/Demo/Test.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<?php
namespace Tests\Demo;
class Test{

public function getHi(): string{
return "Hi Test";
}
class Test
{

public function getHi(): string
{
return "Hi Test";
}
}
15 changes: 15 additions & 0 deletions tests/Unit/RouterEngineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,19 @@

expect($status)->toBe(\Scrawler\Router\Router::NOT_FOUND);

});


it('tests method call with optional parameter',function(): void{

$engine = new \Scrawler\Router\RouterEngine(getCollection(false));
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param');
expect($handler)->toBe('Tests\Demo\Param::allIndex');
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param/12');
expect($handler)->toBe('Tests\Demo\Param::allIndex');
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param/test');
expect($handler)->toBe('Tests\Demo\Param::getTest');
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param/test/12');
expect($handler)->toBe('Tests\Demo\Param::getTest');

});

0 comments on commit 99921ee

Please sign in to comment.