Skip to content

Commit 99921ee

Browse files
author
ipranjal
committed
feat: controllers can have optional params
1 parent 6b84cd3 commit 99921ee

File tree

4 files changed

+44
-8
lines changed

4 files changed

+44
-8
lines changed

src/RouterEngine.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,14 @@ private function getArguments(string $controller, string $method): bool|array
207207
}
208208
// Check weather arguments are passed else throw a 404 error
209209
$classMethod = new \ReflectionMethod($controllerObj, $method);
210-
211-
// Optional parameter introduced in version 3.0.2
212-
if (count($arguments) < count($classMethod->getParameters())) {
210+
$params = $classMethod->getParameters();
211+
// Remove params if it allows null
212+
foreach ($params as $key => $param) {
213+
if ($param->isOptional()) {
214+
unset($params[$key]);
215+
}
216+
}
217+
if (count($arguments) < count($params)) {
213218
$this->debug('Not enough arguments given to the method');
214219

215220
return false;

tests/Demo/Param.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
namespace Tests\Demo;
3+
class Param
4+
{
5+
6+
public function allIndex($id=null)
7+
{
8+
return "Index Test";
9+
}
10+
11+
public function getTest($id=null)
12+
{
13+
return "Test Test";
14+
}
15+
}

tests/Demo/Test.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
<?php
22
namespace Tests\Demo;
3-
class Test{
4-
5-
public function getHi(): string{
6-
return "Hi Test";
7-
}
3+
class Test
4+
{
85

6+
public function getHi(): string
7+
{
8+
return "Hi Test";
9+
}
910
}

tests/Unit/RouterEngineTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,19 @@
110110

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

113+
});
114+
115+
116+
it('tests method call with optional parameter',function(): void{
117+
118+
$engine = new \Scrawler\Router\RouterEngine(getCollection(false));
119+
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param');
120+
expect($handler)->toBe('Tests\Demo\Param::allIndex');
121+
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param/12');
122+
expect($handler)->toBe('Tests\Demo\Param::allIndex');
123+
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param/test');
124+
expect($handler)->toBe('Tests\Demo\Param::getTest');
125+
[$status,$handler,$args,$debug] = $engine->route('GET',uri: '/param/test/12');
126+
expect($handler)->toBe('Tests\Demo\Param::getTest');
127+
113128
});

0 commit comments

Comments
 (0)