From 99921ee5c582093bf0c953024466dc34388fad61 Mon Sep 17 00:00:00 2001 From: ipranjal Date: Fri, 18 Oct 2024 14:37:58 +0530 Subject: [PATCH] feat: controllers can have optional params --- src/RouterEngine.php | 11 ++++++++--- tests/Demo/Param.php | 15 +++++++++++++++ tests/Demo/Test.php | 11 ++++++----- tests/Unit/RouterEngineTest.php | 15 +++++++++++++++ 4 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 tests/Demo/Param.php diff --git a/src/RouterEngine.php b/src/RouterEngine.php index e9dbbd5..1a45669 100644 --- a/src/RouterEngine.php +++ b/src/RouterEngine.php @@ -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; diff --git a/tests/Demo/Param.php b/tests/Demo/Param.php new file mode 100644 index 0000000..f3b0ae3 --- /dev/null +++ b/tests/Demo/Param.php @@ -0,0 +1,15 @@ +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'); + }); \ No newline at end of file