From 1e0414e8384101aceae2c94468e723e3bc5490f7 Mon Sep 17 00:00:00 2001 From: Brooke Bryan Date: Tue, 6 Feb 2024 10:50:25 +0000 Subject: [PATCH] Add an exact path route (#2) --- composer.json | 2 +- src/Routes/ExactPathRoute.php | 36 ++++++++++++++++++++ tests/Routes/ExactPathRouteTest.php | 53 +++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 src/Routes/ExactPathRoute.php create mode 100644 tests/Routes/ExactPathRouteTest.php diff --git a/composer.json b/composer.json index f92ec3b..f0ed732 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ } ], "require": { - "php": ">=7.2", + "php": ">=8.0", "packaged/context": "~1.0", "packaged/helpers": "~2.0" }, diff --git a/src/Routes/ExactPathRoute.php b/src/Routes/ExactPathRoute.php new file mode 100644 index 0000000..e4c20d0 --- /dev/null +++ b/src/Routes/ExactPathRoute.php @@ -0,0 +1,36 @@ +_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; + } +} diff --git a/tests/Routes/ExactPathRouteTest.php b/tests/Routes/ExactPathRouteTest.php new file mode 100644 index 0000000..4ef7293 --- /dev/null +++ b/tests/Routes/ExactPathRouteTest.php @@ -0,0 +1,53 @@ +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()); + } +}