diff --git a/README.md b/README.md index 35054ef..15ef9d3 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ Simple routing library for web applications. # Usage -1. Require kavalanche/security +1. Require kavalanche/router ```bash - composer require kavalanche/security + composer require kavalanche/router ``` 2. Create `Router` instance. diff --git a/composer.json b/composer.json index ca8d5b1..c7d2693 100644 --- a/composer.json +++ b/composer.json @@ -1,22 +1,22 @@ -{ - "name": "kavalanche/router", - "description": "Router component for web applications", - "type": "library", - "authors": [ - { - "name": "Wojtek", - "email": "w.lk@wp.pl" - } - ], - "autoload": { - "psr-4": { - "Kavalanche\\Router\\": "src/" - } - }, - "require": { - - }, - "require-dev": { - "phpunit/phpunit": "^8.4" - } -} +{ + "name": "kavalanche/router", + "description": "Router component for web applications", + "type": "library", + "authors": [ + { + "name": "Wojtek", + "email": "w.lk@wp.pl" + } + ], + "autoload": { + "psr-4": { + "Kavalanche\\Router\\": "src/" + } + }, + "require": { + + }, + "require-dev": { + "phpunit/phpunit": "^8.4" + } +} diff --git a/src/Route.php b/src/Route.php index ce25992..f0e9e4b 100644 --- a/src/Route.php +++ b/src/Route.php @@ -1,5 +1,7 @@ method = $method; $route->path = $path; @@ -21,11 +23,11 @@ class Router { $this->routes[] = $route; } - public function get($path, $callback) { + public function get(string $path, callable $callback) { return $this->request('get', $path, $callback); } - public function post($path, $callback) { + public function post(string $path, callable $callback) { return $this->request('post', $path, $callback); } @@ -35,19 +37,26 @@ class Router { foreach ($this->routes as $route) { $path = str_replace('/', '\/', $route->path); $path = '/^' . $path . '\/?$/'; - if (in_array($requestMethod, $this->allowedMethods, true)) { - if ($requestMethod === $route->method) { - if (preg_match($path, $requestUri['path'], $params) === 1) { - array_shift($params); - call_user_func_array($route->callback, $params); - exit; - } - } + if (in_array($requestMethod, $this->allowedMethods, true) && $requestMethod === $route->method && preg_match($path, $requestUri['path'], $params) === 1) { + array_shift($params); + call_user_func_array($route->callback, $params); + exit; } } http_response_code(404); throw new RouteNotFoundException('Route not found!'); - exit; } + public function isRequestInRoutes(): bool { + $requestMethod = strtolower($_SERVER['REQUEST_METHOD']); + $requestUri = parse_url($_SERVER['REQUEST_URI']); + foreach ($this->routes as $route) { + $path = str_replace('/', '\/', $route->path); + $path = '/^' . $path . '\/?$/'; + if (in_array($requestMethod, $this->allowedMethods, true) && $requestMethod === $route->method && preg_match($path, $requestUri['path'], $params) === 1) { + return true; + } + } + return false; + } }