Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented route grouping, cleaned up public asset handling #7

Merged
merged 1 commit into from
Feb 16, 2023
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,26 @@ $router->get('/', MyController::class . '::index')
$router->post('/', MyController::class . '::index')
```

### Route groups

You can group routes together, this allows you to e.g. define a prefix for a colleciton of routes or apply
middleware to the collection of routes.

You can define a route group like so:
```php
use Math280h\PhpRouter\Route;

$router->group(["prefix" => "test"], [
Route::get('/1', function () {
echo 'Hello World';
}),
Route::get('/2', function () {
echo 'Hello World';
}),
]);
```
This example results in two routes with the paths `/test/1` and `/test/2`

### Adding middleware

The router supports middleware than runs after the connection is accepted but before the request
Expand Down
111 changes: 110 additions & 1 deletion src/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,113 @@ private function makeCallable(): void
}
}
}
}

/**
* Route construction
*/

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function get(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "GET", $callback, $middleware);
}

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function post(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "POST", $callback, $middleware);
}

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function put(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "PUT", $callback, $middleware);
}

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function delete(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "DELETE", $callback, $middleware);
}

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function options(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "OPTIONS", $callback, $middleware);
}

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function head(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "HEAD", $callback, $middleware);
}

/**
* @param string $path
* @param callable|string $callback
* @param array<string> $middleware
* @return Route
*/
public static function patch(
string $path,
callable|string $callback,
array $middleware = []
): Route
{
return new Route($path, "PATCH", $callback, $middleware);
}
}
46 changes: 17 additions & 29 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,24 @@ class Router
*/
private array $middlewares;

public function __construct(string $public_directory = "")
/**
* Create route group
*
* @param array<string> $attributes
* @param array<Route> $routes
* @return void
*/
public function group(array $attributes, array $routes): void
{
$this->loadPublic($public_directory);
foreach ($routes as $route) {
if (array_key_exists("prefix", $attributes)) {
$route->path = (!str_starts_with($attributes["prefix"], "/") ? "/" . $attributes["prefix"]:$attributes["prefix"]) . $route->path;
}
if (array_key_exists("middleware", $attributes)) {
$route->middleware[] = $attributes["middleware"];
}
$this->addRoute($route);
}
}

/**
Expand Down Expand Up @@ -142,33 +157,6 @@ public function addMiddleware(string $name, Closure $middleware): void
$this->middlewares[$name] = $middleware;
}

/**
* Load resource in public folder
*
* @param string $public_directory
* @return void
*/
private function loadPublic(string $public_directory = ""): void
{
if ($public_directory === "") {
$public_directory = dirname(__DIR__, 2) . '/public';
}

$public_resources = new RecursiveTreeIterator(
new RecursiveDirectoryIterator(
$public_directory,
FilesystemIterator::SKIP_DOTS));

foreach ($public_resources as $public_resource) {
$path = explode('public/', $public_resource)[1];
if (!str_ends_with($path, '.php')) {
$this->get($path, function() use ($public_resource) {
echo file_get_contents($public_resource);
});
}
}
}

/**
* Run Router
*
Expand Down
2 changes: 1 addition & 1 deletion tests/RouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class RouterTest extends TestCase

public function setUp(): void
{
$path = getcwd() . "/server";
$path = getcwd() . "/public";
$this->process = new Process(["php", "-S", "localhost:8080", "-t", $path]);
$this->process->start();

Expand Down
File renamed without changes.
33 changes: 33 additions & 0 deletions tests/public/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

require '../../vendor/autoload.php';

use Math280h\PhpRouter\Route;
use Math280h\PhpRouter\Router;

session_start();

$router = new Router();
$router->get('/', function () {
echo 'Hello World';
});

$router->get('/yeet', function () {
echo 'Hello World';
});


$router->group(["prefix" => "test"], [
Route::get('/1', function () {
echo 'Hello World';
}),
Route::get('/2', function () {
echo 'Hello World';
}),
]);

$router->addMiddleware("log", function ($request) {
print_r($request);
});

$router->run();
18 changes: 0 additions & 18 deletions tests/server/index.php

This file was deleted.