Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
230 changes: 198 additions & 32 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,230 @@
# Marea Turbo Router
#### PHP Version 8.1^
<img src="mareaGif/marea.gif" alt="VRUMMMMMMMMMMMMMMMM" width="50%"/>

<p align="center">
<a href="https://packagist.org/packages/marrios/mareaturborouter"><img src="https://img.shields.io/packagist/dt/marrios/mareaturborouter" alt="Total Downloads"</a>
<p>
<a href="https://packagist.org/packages/marrios/mareaturborouter"><img src="https://img.shields.io/packagist/dt/marrios/mareaturborouter" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/marrios/mareaturborouter"><img src="https://img.shields.io/packagist/v/marrios/mareaturborouter" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/marrios/mareaturborouter"><img src="https://img.shields.io/packagist/l/marrios/mareaturborouter" alt="License"></a>
</p>

@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.

<br>
```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
<?php

require_once("vendor/autoload.php");
require_once "vendor/autoload.php";

use MareaTurbo\Router;

use MareaTurbo\Route;

class ControllerTeste
class PostController
{
public function __construct()
{}

#[Route("/teste/{id}", "GET", "route.name")]
public function teste($request)
#[Route("/posts/{id}", "GET")]
public function show($request)
{
// get all parameters
$request->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
<br>
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

<br>
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)
16 changes: 10 additions & 6 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
namespace MareaTurbo;
use MareaTurbo\MareaTurboException;
use ReflectionClass;
use MareaTurbo\RouteParameters;

class Controller
{
Expand Down Expand Up @@ -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);
}
Expand Down
5 changes: 2 additions & 3 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@

namespace MareaTurbo;

use AllowDynamicProperties;

#[AllowDynamicProperties]
class Request
{
private Route $route;

/**
*
*/
Expand Down
13 changes: 5 additions & 8 deletions src/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@

namespace MareaTurbo;

use MareaTurbo\RouteParameters;
use Attribute;

#[Attribute]
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Route
{
public String $path;
public HttpMethod $method;
public string $name;
protected array $inputBag;
protected array $inputBag = [];

/**
*
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down
26 changes: 10 additions & 16 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Expand All @@ -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;
Expand Down
Loading
Loading