From 826beee95035e9185d0c54fea1c238edd0b2d907 Mon Sep 17 00:00:00 2001 From: Samuel Date: Mon, 9 Nov 2026 08:45:30 -0300 Subject: [PATCH 1/2] Fix core routing bugs and harden dependency injection - Initialize Route::$inputBag so $request->all() works on static routes - Only instantiate #[Route] attributes, ignore other method attributes - Normalize leading/trailing slashes when matching routes - URL-decode dynamic route parameters - Resolve scalar/untyped constructor params via default or null, and throw a clear MareaTurboException instead of crashing - Declare Request::$route instead of using dynamic properties - Compute the accessed route once; guard missing CLI args - Remove dead code (getUri, unused RouteParameters import) - Add tests for all of the above Co-Authored-By: Claude Opus 5.5 --- src/Controller.php | 16 ++++++++++------ src/Request.php | 5 ++--- src/Route.php | 11 ++++------- src/Router.php | 26 ++++++++++--------------- tests/Unit/ControllerTest.php | 36 +++++++++++++++++++++++++++++++++++ tests/Unit/RouteTest.php | 22 ++++++++++++++++++++- 6 files changed, 83 insertions(+), 33 deletions(-) create mode 100644 tests/Unit/ControllerTest.php diff --git a/src/Controller.php b/src/Controller.php index 54f13c1..f1e8ab6 100644 --- a/src/Controller.php +++ b/src/Controller.php @@ -4,7 +4,6 @@ namespace MareaTurbo; use MareaTurbo\MareaTurboException; use ReflectionClass; -use MareaTurbo\RouteParameters; class Controller { @@ -64,11 +63,16 @@ private function recursiveDependenciesBuild(ReflectionClass $reflectionControlle $arguments = array(); foreach($dependencies as $dependency){ - if(class_exists($dependency->getType()->getName())) { - $dependencyClassName = $dependency->getType()->getName(); - $dependencyReflectionClass = new ReflectionClass($dependencyClassName); - $arguments[] = $this->recursiveDependenciesBuild($dependencyReflectionClass); - } + $type = $dependency->getType(); + if($type instanceof \ReflectionNamedType && !$type->isBuiltin() && class_exists($type->getName())) { + $arguments[] = $this->recursiveDependenciesBuild(new ReflectionClass($type->getName())); + } elseif($dependency->isDefaultValueAvailable()) { + $arguments[] = $dependency->getDefaultValue(); + } elseif($dependency->allowsNull()) { + $arguments[] = null; + } else { + throw new MareaTurboException("Cannot resolve dependency \${$dependency->getName()} of {$reflectionControllerInstance->getName()}"); + } } return $reflectionControllerInstance->newInstanceArgs($arguments); } diff --git a/src/Request.php b/src/Request.php index 53550ea..b2938bd 100644 --- a/src/Request.php +++ b/src/Request.php @@ -4,11 +4,10 @@ namespace MareaTurbo; -use AllowDynamicProperties; - -#[AllowDynamicProperties] class Request { + private Route $route; + /** * */ diff --git a/src/Route.php b/src/Route.php index c101965..bdad57f 100644 --- a/src/Route.php +++ b/src/Route.php @@ -4,7 +4,6 @@ namespace MareaTurbo; -use MareaTurbo\RouteParameters; use Attribute; #[Attribute] @@ -13,7 +12,7 @@ class Route public String $path; public HttpMethod $method; public string $name; - protected array $inputBag; + protected array $inputBag = []; /** * @@ -46,7 +45,7 @@ public function isMatch(Route $route): bool if (substr($value, 0, 1) != "{" || substr($value, -1) != "}") { return false; } - $this->inputBag[substr($value, 1, -1)] = htmlspecialchars(trim(addslashes($accessedRoute[$key]))); + $this->inputBag[substr($value, 1, -1)] = htmlspecialchars(trim(addslashes(rawurldecode($accessedRoute[$key])))); } } return true; @@ -57,10 +56,8 @@ public function isMatch(Route $route): bool */ public function routeStringToArray(string $string): array { - if (substr($string, -1) == "/") { - $string = substr($string, 0, -1); - } - return explode('/', $string); + // "/post/1", "post/1" and "post/1/" are the same route + return explode('/', trim($string, '/')); } public function getInputBag(): array diff --git a/src/Router.php b/src/Router.php index c5274ce..b182c5f 100644 --- a/src/Router.php +++ b/src/Router.php @@ -34,23 +34,23 @@ public function middleware(String $middleware, $httpStatusCode) */ private function run(): void { + $accessedRoute = $this->getAccessedRoute(); foreach ($this->controllers as $controller) { $reflectionController = new ReflectionClass($controller); foreach ($reflectionController->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { - $this->getRouteAttribute($method, $controller); + $this->getRouteAttribute($method, $controller, $accessedRoute); } } http_response_code(404); } - private function getRouteAttribute($method, $controller) + private function getRouteAttribute(ReflectionMethod $method, string $controller, Route $accessedRoute) { - if ($method->getAttributes()) { - foreach ($method->getAttributes() as $route) { - $routeInstance = $route->newInstance(); - if ($routeInstance->isMatch($this->getAccessedRoute())) { - return $this->invokeController($method, $controller, $routeInstance); - } + // only #[Route] attributes; other attributes on the method are ignored + foreach ($method->getAttributes(Route::class) as $route) { + $routeInstance = $route->newInstance(); + if ($routeInstance->isMatch($accessedRoute)) { + return $this->invokeController($method, $controller, $routeInstance); } } } @@ -72,17 +72,11 @@ private function isCli() private function getAccessedRoute() { global $argv; - $route = $this->isCli() ? $argv[2] : explode("?", $_SERVER['REQUEST_URI'])[0]; - $method = $this->isCli() ? $argv[1] : explode("?", $_SERVER['REQUEST_METHOD'])[0]; + $route = $this->isCli() ? ($argv[2] ?? '/') : explode("?", $_SERVER['REQUEST_URI'])[0]; + $method = $this->isCli() ? ($argv[1] ?? 'GET') : $_SERVER['REQUEST_METHOD']; return new Route($route, $method); } - private function getUri(): string - { - global $argv; - return $this->isCli() ? $argv[2] : explode("?", $_SERVER['REQUEST_URI'])[0]; - } - private function endLifeCycle() { exit; diff --git a/tests/Unit/ControllerTest.php b/tests/Unit/ControllerTest.php new file mode 100644 index 0000000..acecb5d --- /dev/null +++ b/tests/Unit/ControllerTest.php @@ -0,0 +1,36 @@ +dep, $this->limit, $request->all()]; } +} +class CtrlUnresolvable +{ + public function __construct(int $required) {} + public function show($request) {} +} + +function matchedRequest(): \MareaTurbo\Request +{ + $route = new \MareaTurbo\Route("/x/{id}", "GET"); + $route->isMatch(new \MareaTurbo\Route("/x/7", "GET")); + return new \MareaTurbo\Request($route); +} + +test("builds class dependencies and uses defaults for scalar parameters", function () { + [$dep, $limit, $params] = (new \MareaTurbo\Controller(CtrlWithDeps::class))->runMethod("show", matchedRequest()); + + expect($dep)->toBeInstanceOf(CtrlDep::class) + ->and($limit)->toBe(10) + ->and($params)->toBe(["id" => "7"]); +}); + +test("throws a clear exception when a dependency cannot be resolved", function () { + (new \MareaTurbo\Controller(CtrlUnresolvable::class))->runMethod("show", matchedRequest()); +})->throws(\MareaTurbo\MareaTurboException::class, 'Cannot resolve dependency $required'); + +test("throws when the method does not exist", function () { + (new \MareaTurbo\Controller(CtrlWithDeps::class))->runMethod("nope", matchedRequest()); +})->throws(\MareaTurbo\MareaTurboException::class, "Method not found"); diff --git a/tests/Unit/RouteTest.php b/tests/Unit/RouteTest.php index 517e498..f67ddd4 100644 --- a/tests/Unit/RouteTest.php +++ b/tests/Unit/RouteTest.php @@ -34,4 +34,24 @@ $match = $route->isMatch($currentRoute); expect($match)->toBeFalse(); -}); \ No newline at end of file +}); + +test("input bag is empty, not an error, for routes without parameters", function () { + $route = new \MareaTurbo\Route("/post", "GET"); + $route->isMatch(new \MareaTurbo\Route("/post", "GET")); + + expect($route->getInputBag())->toBe([]); +}); + +test("leading and trailing slashes do not matter", function () { + $route = new \MareaTurbo\Route("/post/{id}", "GET"); + + expect($route->isMatch(new \MareaTurbo\Route("post/1/", "GET")))->toBeTrue(); +}); + +test("dynamic parameters are url-decoded and captured", function () { + $route = new \MareaTurbo\Route("/user/{name}", "GET"); + $route->isMatch(new \MareaTurbo\Route("/user/jo%C3%A3o", "GET")); + + expect($route->getInputBag())->toBe(["name" => "joão"]); +}); From 80d5a4242d1f4d13228609e88e3d88f10eb1fe38 Mon Sep 17 00:00:00 2001 From: Samuel Date: Mon, 9 Nov 2026 08:46:57 -0300 Subject: [PATCH 2/2] Rewrite README and allow repeated #[Route] attributes README: fix broken image and badge markup, add web server setup, parameter, DI, middleware ordering and matching-rule docs. Route attribute is now IS_REPEATABLE so one method can serve several routes, as documented. Co-Authored-By: Claude Opus 5.5 --- README.md | 230 +++++++++++++++++++++++++++++++++------ src/Route.php | 2 +- tests/Unit/RouteTest.php | 12 ++ 3 files changed, 211 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c6ef451..06ae5a3 100644 --- a/README.md +++ b/README.md @@ -1,64 +1,230 @@ # Marea Turbo Router -#### PHP Version 8.1^ -VRUMMMMMMMMMMMMMMMM -

- Total Downloads +

+ Total Downloads Latest Stable Version License

-@marriosdev +A tiny, zero-dependency HTTP router for PHP 8.1+. Routes are declared with PHP attributes right on your controller methods: no route files, no config. -
+```php +#[Route("/users/{id}", "GET")] +public function show($request) { ... } +``` -# Starting +Created by [@marriosdev](https://github.com/marriosdev). -```php +## Contents + +- [Installation](#installation) +- [Quick start](#quick-start) +- [Web server setup](#web-server-setup) +- [Defining routes](#defining-routes) +- [Reading parameters](#reading-parameters) +- [Dependency injection](#dependency-injection) +- [Middleware](#middleware) +- [CLI mode](#cli-mode) +- [How matching works](#how-matching-works) +- [Running the tests](#running-the-tests) + +## Installation + +```bash composer require marrios/mareaturborouter ``` -### Copy -```php +Requires **PHP 8.1 or newer**. + +## Quick start + +Create `index.php`: +```php all(); - - // get only id parameter - echo $request->only(["id"])['id']; + echo "Post " . $request->only(["id"])["id"]; } } -// Register controllers (new Router())->controllers([ - ControllerTeste::class + PostController::class, ]); ``` -In your browser, access the URL: http://localhost/teste/123 -
-And you will see the result: 123 +Run it with PHP's built-in server: + +```bash +php -S localhost:8000 index.php +``` + +Open http://localhost:8000/posts/123 and you'll see `Post 123`. + +## Web server setup -
+Every request has to reach `index.php`. The built-in server above already does that. In production: -You can run this route in CLI mode +**Apache** (`.htaccess` next to `index.php`): -```shell -php .\index.php GET /teste/123 +```apache +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^ index.php [QSA,L] ``` + +**Nginx**: + +```nginx +location / { + try_files $uri $uri/ /index.php?$query_string; +} +``` + +## Defining routes + +```php +#[Route(string $path, string $method, string $name = '')] +``` + +| Argument | Description | +|-----------|-------------| +| `$path` | URL path. Segments wrapped in `{}` are dynamic parameters. | +| `$method` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` or `HEAD` (case-insensitive). Anything else throws `MareaTurboException`. | +| `$name` | Optional label for the route (informational for now). | + +A method can carry several routes: + +```php +class UserController +{ + #[Route("/users", "GET")] + public function index($request) { ... } + + #[Route("/users", "POST")] + public function store($request) { ... } + + #[Route("/users/{id}", "PUT")] + #[Route("/users/{id}", "PATCH")] + public function update($request) { ... } + + #[Route("/categories/{category}/posts/{post}", "GET")] + public function postInCategory($request) { ... } +} +``` + +Register every controller with the router: + +```php +(new Router())->controllers([ + UserController::class, + PostController::class, +]); +``` + +## Reading parameters + +Every route method gets a `MareaTurbo\Request` argument: + +```php +#[Route("/categories/{category}/posts/{post}", "GET")] +public function show($request) +{ + $request->all(); // ["category" => "10", "post" => "5"] + $request->only(["post"]); // ["post" => "5"] +} +``` + +- Values are URL-decoded (`/users/jo%C3%A3o` gives `joão`). +- Values are escaped with `htmlspecialchars` and `addslashes`, so treat them as strings. +- `Request` only holds **path** parameters. Read the query string and body the usual way (`$_GET`, `$_POST`, `file_get_contents('php://input')`). + +## Dependency injection + +Controller constructors get their dependencies automatically, recursively: + +```php +class UserRepository +{ + public function __construct(private Database $db) {} +} + +class UserController +{ + public function __construct(private UserRepository $users, private int $perPage = 20) {} + + #[Route("/users", "GET")] + public function index($request) { ... } +} +``` + +How each constructor parameter gets its value: + +1. A class type → built recursively. +2. Otherwise, its default value. +3. Otherwise, `null` if it's nullable or has no type. +4. Otherwise → `MareaTurboException("Cannot resolve dependency $param of Class")`. + +Interfaces can't be resolved. Type-hint concrete classes. + +## Middleware + +A middleware is any class with a `handle(): bool` method. Return `false` to stop the request with the given HTTP status code: + +```php +class AuthMiddleware +{ + public function handle(): bool + { + return isset($_SERVER['HTTP_AUTHORIZATION']); + } +} + +(new Router()) + ->middleware(AuthMiddleware::class, 401) + ->controllers([UserController::class]); +``` + +> Call `middleware()` **before** `controllers()`. `controllers()` dispatches the request and ends the script, so nothing chained after it runs. Middleware applies to every controller registered on that router. + +## CLI mode + +Routes can be called from the terminal, which is handy for scripts and debugging: + +```bash +php index.php GET /posts/123 +``` + +## How matching works + +- Controllers are checked in the order you register them, then their public methods in order. **The first match wins**, its method runs, and the script ends. +- Leading and trailing slashes are ignored: `/posts/1`, `posts/1` and `/posts/1/` are the same. +- The query string is ignored when matching: `/posts/1?page=2` matches `/posts/{id}`. +- Without a match, the response status is `404` and nothing is printed. Print your own "not found" page after `controllers()`: + +```php +(new Router())->controllers([...]); + +echo "Page not found"; // only reached when no route matched +``` + +## Running the tests + +```bash +composer install +vendor/bin/pest +``` + +## License + +[GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.html) diff --git a/src/Route.php b/src/Route.php index bdad57f..c99b46b 100644 --- a/src/Route.php +++ b/src/Route.php @@ -6,7 +6,7 @@ use Attribute; -#[Attribute] +#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)] class Route { public String $path; diff --git a/tests/Unit/RouteTest.php b/tests/Unit/RouteTest.php index f67ddd4..6a530ee 100644 --- a/tests/Unit/RouteTest.php +++ b/tests/Unit/RouteTest.php @@ -55,3 +55,15 @@ expect($route->getInputBag())->toBe(["name" => "joão"]); }); + +test("a method can declare several routes", function () { + $method = new ReflectionMethod(new class { + #[\MareaTurbo\Route("/a", "PUT")] + #[\MareaTurbo\Route("/a", "PATCH")] + public function update() {} + }, "update"); + + $methods = array_map(fn ($a) => $a->newInstance()->method->name, $method->getAttributes(\MareaTurbo\Route::class)); + + expect($methods)->toBe(["PUT", "PATCH"]); +});