Repository: robsonvleite/router
Branch: master
Commit: f9117a615927
Files: 17
Total size: 37.9 KB
Directory structure:
gitextract_3ldu3wt6/
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── composer.json
├── exemple/
│ ├── controller/
│ │ ├── .htaccess
│ │ ├── Http/
│ │ │ ├── Group.php
│ │ │ ├── Guest.php
│ │ │ ├── Middlewares.php
│ │ │ └── User.php
│ │ ├── Test/
│ │ │ ├── Coffee.php
│ │ │ └── Name.php
│ │ └── index.php
│ └── spoofing/
│ ├── .htaccess
│ └── index.php
└── src/
├── Dispatch.php
├── Router.php
└── RouterTrait.php
================================================
FILE CONTENTS
================================================
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/robsonvleite/uploader).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer).
- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date.
- **Create topic branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
**Happy Coffee**!
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2018 Robson V. Leite @CoffeeCode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# Router @CoffeeCode
[](https://twitter.com/robsonvleite)
[](https://github.com/robsonvleite/router)
[](https://packagist.org/packages/coffeecode/router)
[](https://github.com/robsonvleite/router/releases)
[](LICENSE)
[](https://scrutinizer-ci.com/g/robsonvleite/router)
[](https://packagist.org/packages/coffeecode/router)
###### Small, simple and uncomplicated. The router is a PHP route components with abstraction for MVC. Prepared with RESTfull verbs (GET, POST, PUT, PATCH and DELETE), works on its own layer in isolation and can be integrated without secrets to your application.
Pequeno, simples e descomplicado. O router é um componentes de rotas PHP com abstração para MVC. Preparado com verbos
RESTfull (GET, POST, PUT, PATCH e DELETE), trabalha em sua própria camada de forma isolada e pode ser integrado sem
segredos a sua aplicação.
## About CoffeeCode
###### CoffeeCode is a set of small and optimized PHP components for common tasks. Held by Robson V. Leite and the UpInside team. With them you perform routine tasks with fewer lines, writing less and doing much more.
CoffeeCode é um conjunto de pequenos e otimizados componentes PHP para tarefas comuns. Mantido por Robson V. Leite e a
equipe UpInside. Com eles você executa tarefas rotineiras com poucas linhas, escrevendo menos e fazendo muito mais.
### Highlights
- Router class with all RESTful verbs (Classe router com todos os verbos RESTful)
- Optimized dispatch with total decision control (Despacho otimizado com controle total de decisões)
- Requesting Spoofing for Local Verbalization (Falsificador (Spoofing) de requisição para verbalização local)
- It's very simple to create routes for your application or API (É muito simples criar rotas para sua aplicação ou API)
- Trigger and data carrier for the controller (Gatilho e transportador de dados para o controloador)
- Composer ready and PSR-2 compliant (Pronto para o composer e compatível com PSR-2)
## Installation
Router is available via Composer:
```bash
"coffeecode/router": "2.0.*"
```
or run
```bash
composer require coffeecode/router
```
## Documentation
###### For details on how to use the router, see the sample folder with details in the component directory. To use the router you need to redirect your route routing navigation (index.php) where all traffic must be handled. The example below shows how:
Para mais detalhes sobre como usar o router, veja a pasta de exemplo com detalhes no diretório do componente. Para usar
o router é preciso redirecionar sua navegação para o arquivo raiz de rotas (index.php) onde todo o tráfego deve ser
tratado. O exemplo abaixo mostra como:
#### Apache
```apacheconfig
RewriteEngine On
#Options All -Indexes
## ROUTER WWW Redirect.
#RewriteCond %{HTTP_HOST} !^www\. [NC]
#RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
## ROUTER HTTPS Redirect
#RewriteCond %{HTTP:X-Forwarded-Proto} !https
#RewriteCond %{HTTPS} off
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ROUTER URL Rewrite
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=/$1 [L,QSA]
```
#### Nginx
````nginxconfig
location / {
if ($script_filename !~ "-f"){
rewrite ^(.*)$ /index.php?route=/$1 break;
}
}
````
##### Routes
```php
<?php
use CoffeeCode\Router\Router;
$router = new Router("https://www.youdomain.com");
/**
* routes
* The controller must be in the namespace Test\Controller
* this produces routes for route, route/$id, route/{$id}/profile, etc.
*/
$router->namespace("Test");
$router->get("/route", "Controller:method");
$router->post("/route/{id}", "Controller:method");
$router->put("/route/{id}/profile", "Controller:method");
$router->patch("/route/{id}/profile/{photo}", "Controller:method");
$router->delete("/route/{id}", "Controller:method");
/**
* group by routes and namespace
* this produces routes for /admin/route and /admin/route/$id
* The controller must be in the namespace Dash\Controller
*/
$router->group("admin")->namespace("Dash");
$router->get("/route", "Controller:method");
$router->post("/route/{id}", "Controller:method");
/**
* sub group
*/
$router->group("admin/support");
$router->get("/tickets", "Controller:method");
$router->post("/ticket/{id}", "Controller:method");
/**
* Group Error
* This monitors all Router errors. Are they: 400 Bad Request, 404 Not Found, 405 Method Not Allowed and 501 Not Implemented
*/
$router->group("error")->namespace("Test");
$router->get("/{errcode}", "Coffee:notFound");
/**
* This method executes the routes
*/
$router->dispatch();
/*
* Redirect all errors
*/
if ($router->error()) {
$router->redirect("/error/{$router->error()}");
}
```
##### Named
```php
<?php
use CoffeeCode\Router\Router;
$router = new Router("https://www.youdomain.com");
/**
* routes
* The controller must be in the namespace Test\Controller
*/
$router->namespace("Test")->group("name");
$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello");
$router->get("/redirect", "Name:redirect", "name.redirect");
/**
* This method executes the routes
*/
$router->dispatch();
/*
* Redirect all errors
*/
if ($router->error()) {
$router->redirect("name.hello");
}
```
###### Named Controller Example
```php
<?php
class Name
{
public function __construct($router)
{
$this->router = $router;
}
public function home(): void
{
echo "<h1>Home</h1>";
echo "<p>", $this->router->route("name.home"), "</p>";
echo "<p>", $this->router->route("name.hello"), "</p>";
echo "<p>", $this->router->route("name.redirect"), "</p>";
}
public function redirect(): void
{
$this->router->redirect("name.hello");
}
}
```
###### Named Params
````php
<?php
use CoffeeCode\Router\Router;
$router = new Router("https://www.youdomain.com");
$this->router->route("name.params", [
"category" => 22,
"page" => 2
]);
//result
//https://www.youdomain.com/name/params/22/page/2
$this->router->route("name.params", [
"category" => 22,
"page" => 2,
"argument1" => "most filter",
"argument2" => "most search"
]);
//result
//https://www.youdomain.com/name/params/22/page/2?argument1=most+filter&argument2=most+search
````
##### Callable
```php
<?php
use CoffeeCode\Router\Router;
$router = new Router("https://www.youdomain.com");
/**
* GET httpMethod
*/
$router->get("/", function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>GET :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});
/**
* GET httpMethod and Route
*/
$router->get("/", function ($data, Router $route) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>GET :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
var_dump($route->current());
});
/**
* POST httpMethod
*/
$router->post("/", function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>POST :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});
/**
* PUT spoofing and httpMethod
*/
$router->put("/", function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>PUT :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});
/**
* PATCH spoofing and httpMethod
*/
$router->patch("/", function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>PATCH :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});
/**
* DELETE spoofing and httpMethod
*/
$router->delete("/", function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>DELETE :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});
$router->dispatch();
```
##### Simple Middleware
```php
<?php
use CoffeeCode\Router\Router;
$router = new Router("https://www.youdomain.com");
//simple
$router->get("/edit/{id}", "Coffee:edit", middleware: \Http\Guest::class);
$router->get("/denied", "Coffee:denied", "coffe.denied", \Http\Group::class);
//multiple
$router->get("/logado", "Coffee:logged", middleware: [\Http\Guest::class, \Http\Group::class]);
//callable
$router->get("/call", function ($data, Router $router){
//code here
}, middleware: \Http\Guest::class);
```
##### Simple Middleware Group
```php
<?php
use CoffeeCode\Router\Router;
$router = new Router("https://www.youdomain.com");
//group single or multiple
$router->group("name", \Http\Guest::class);
$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello");
$router->get("/redirect", "Name:redirect", "name.redirect");
```
##### Simple Middleware Class Example
```php
<?php
namespace Http;
use CoffeeCode\Router\Router;
class User
{
public function handle(Router $router): bool
{
$user = true;
if ($user) {
var_dump($router->current());
return true;
}
return false;
}
}
```
##### Form Spoofing
###### This example shows how to access the routes (PUT, PATCH, DELETE) from the application. You can see more details in the sample folder. From an attention to the _method field, it can be of the hidden type.
Esse exemplo mostra como acessar as rotas (PUT, PATCH, DELETE) a partir da aplicação. Você pode ver mais detalhes na
pasta de exemplo. De uma atenção para o campo _method, ele pode ser do tipo hidden.
```html
<form action="" method="POST">
<select name="_method">
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="PATCH">PATCH</option>
<option value="DELETE">DELETE</option>
</select>
<input type="text" name="first_name" value="Robson"/>
<input type="text" name="last_name" value="Leite"/>
<input type="text" name="email" value="cursos@upinside.com.br"/>
<button>CoffeeCode</button>
</form>
```
##### PHP cURL example
```php
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost/coffeecode/router/example/spoofing/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "first_name=Robson&last_name=Leite&email=cursos%40upinside.com.br",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
```
## Contributing
Please see [CONTRIBUTING](https://github.com/robsonvleite/router/blob/master/CONTRIBUTING.md) for details.
## Support
###### Security: If you discover any security related issues, please email cursos@upinside.com.br instead of using the issue tracker.
Se você descobrir algum problema relacionado à segurança, envie um e-mail para cursos@upinside.com.br em vez de usar o
rastreador de problemas.
Thank you
## Credits
- [Robson V. Leite](https://github.com/robsonvleite) (Developer)
- [UpInside Treinamentos](https://github.com/upinside) (Team)
- [All Contributors](https://github.com/robsonvleite/router/contributors) (This Rock)
## License
The MIT License (MIT). Please see [License File](https://github.com/robsonvleite/router/blob/master/LICENSE) for more
information.
================================================
FILE: composer.json
================================================
{
"name": "coffeecode/router",
"description": "A classic CoffeeCode Router is easy, fast and extremely uncomplicated. Create and manage your routes in minutes!",
"keywords": [
"CoffeeCode",
"UpInside",
"Router",
"Route",
"Routes"
],
"homepage": "http://www.upinside.com.br",
"license": "MIT",
"authors": [
{
"name": "Robson V. Leite",
"email": "cursos@upinside.com.br",
"role": "Developer"
}
],
"require": {
"php": ">=8.0"
},
"autoload": {
"psr-4": {
"CoffeeCode\\Router\\": "src"
}
}
}
================================================
FILE: exemple/controller/.htaccess
================================================
RewriteEngine On
Options All -Indexes
# ROUTER WWW Redirect.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ROUTER HTTPS Redirect
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ROUTER URL Rewrite
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=/$1 [L,QSA]
================================================
FILE: exemple/controller/Http/Group.php
================================================
<?php
namespace Http;
class Group
{
public function handle(): bool
{
echo "<p><i>O middleware <b>Group</b> foi executado!</i></p>";
$group = true;
if ($group) {
return true;
}
return false;
}
}
================================================
FILE: exemple/controller/Http/Guest.php
================================================
<?php
namespace Http;
class Guest
{
public function handle(): bool
{
echo "<p><i>O middleware <b>Guest</b> foi executado!</i></p>";
$guest = true;
if ($guest) {
return true;
}
return false;
}
}
================================================
FILE: exemple/controller/Http/Middlewares.php
================================================
<?php
namespace Http;
class Middlewares
{
const GUEST = Guest::class;
const USER = User::class;
CONST GROUP = Group::class;
}
================================================
FILE: exemple/controller/Http/User.php
================================================
<?php
namespace Http;
use CoffeeCode\Router\Router;
class User
{
public function handle(Router $router): bool
{
echo "<p><i>O middleware <b>User</b> foi executado!</i></p>";
$user = filter_input(INPUT_GET, "user", FILTER_VALIDATE_BOOL);
if ($user) {
return true;
}
echo "<h1>Acces Denied!</h1>";
echo "<a href='{$router->route("coffe.denied", ["user" => true])}'>Simular Usuário</a>";
return false;
}
}
================================================
FILE: exemple/controller/Test/Coffee.php
================================================
<?php
namespace Test;
use CoffeeCode\Router\Router;
/**
* Class Coffee MVC :: CONTROLLER
* @package Test
*/
class Coffee
{
/**
* Coffee constructor.
*/
public function __construct(Router $router)
{
$url = BASE;
$rand = rand(44, 244);
echo "<h1>Router @CoffeeCode</h1>";
echo "<p>Normal routes:</p>";
echo "<nav>
<a href='{$url}'>Home</a> |
<a href='{$url}/edit/{$rand}'>Edit</a> |
<a href='{$url}/logado/?user=true'>Logado</a> |
<a href='{$router->route("coffe.denied")}'>Negado</a> |
<a href='{$url}/error/'>Error</a>
</nav>";
echo "<p>Group routes:</p>";
echo "<nav>
<a href='{$url}/admin'>Admin</a> |
<a href='{$url}/admin/user/{$rand}'>Edit User</a> |
<a href='{$url}/admin/user/{$rand}/profile'>Perfil</a> |
<a href='{$url}/admin/user/{$rand}/profile/imagem-{$rand}.jpg'>Photo</a>
</nav>";
echo "<p>Named and call routes:</p>";
echo "<nav>
<a href='{$url}/name'>Named</a> |
<a href='{$url}/call'>Call Current</a> |
<a href='{$url}/call/coffecode'>Call Current + App</a>
</nav>";
}
/**
* @param array $data
*/
public function home(array $data): void
{
echo "<h3>", __METHOD__, "::", $_SERVER["REQUEST_METHOD"], "</h3><hr>";
echo "<pre>", print_r($data, true), "</pre>";
}
/**
* @param array $data
*/
public function edit(array $data): void
{
echo "<h3>", __METHOD__, "::", $_SERVER["REQUEST_METHOD"], "</h3><hr>";
echo "<form name='coffeecode' method='post' enctype='multipart/form-data'>
<input name=\"first_name\" value=\"Robson\">
<input name=\"last_name\" value=\"V. Leite\">
<input name=\"email\" value=\"cursos@upinside.com.br\">
<button>@CoffeeCode</button>
</form>";
echo "<pre>", print_r($data, true), "</pre>";
}
/**
* @param array $data
*/
public function notfound(array $data): void
{
echo "<h3>Whoops!</h3>", "<pre>", print_r($data, true), "</pre>";
}
/**
* @param array $data
*/
public function admin(array $data): void
{
echo "<h3>Admin Group:</h3>", "<pre>", print_r($data, true), "</pre>";
}
/**
* @param array $data
*/
public function logged(array $data)
{
echo "<h3>Logged</h3>", "<p>Essa tela simula execução de múltiplos middlewares</p>", "<pre>", print_r(
$data,
true
), "</pre>";
}
/**
* @param array $data
*/
public function denied(array $data)
{
echo "<h3>Acessou com sucesso: (Access Denied)</h3>", "<pre>", print_r($data, true), "</pre>";
}
}
================================================
FILE: exemple/controller/Test/Name.php
================================================
<?php
namespace Test;
use CoffeeCode\Router\Router;
class Name
{
/** @var Router */
private Router $router;
public function __construct($router)
{
$this->router = $router;
$params = ["category" => 23213, "page" => 2];
echo "<p>Named routes:</p>";
echo "<nav>
<a href='{$this->router->route("name.home")}'>Home</a> |
<a href='{$this->router->route("name.hello")}'>Hello</a> |
<a href='{$this->router->route("name.params", $params)}'>Params</a> |
<a href='{$this->router->route("name.redirect")}'>Redirect Back</a>
</nav>";
}
public function home(): void
{
echo "<h3>Home</h3>";
echo "<p>", $this->router->route("name.home"), "</p>";
echo "<p>", $this->router->route("name.hello"), "</p>";
echo "<p>", $this->router->route("name.redirect"), "</p>";
}
public function hello(): void
{
echo "<h3>Hello World</h3>";
echo "<a href='{$this->router->route("name.params", ["category" => 6, "page" => 1])}'>Route Params</a>";
}
public function params(array $data): void
{
echo "<h3>Params</h3>";
var_dump($data, $this->router->current());
}
public function redirect(array $data): void
{
if ($data) {
$this->router->redirect("name.params", $data);
}
$this->router->redirect(BASE);
}
}
================================================
FILE: exemple/controller/index.php
================================================
<?php
require dirname(__DIR__, 2) . "/vendor/autoload.php";
require __DIR__ . "/Test/Coffee.php";
require __DIR__ . "/Test/Name.php";
/*
* Middleware example classes
*/
require __DIR__ . "/Http/Middlewares.php";
require __DIR__ . "/Http/Guest.php";
require __DIR__ . "/Http/User.php";
require __DIR__ . "/Http/Group.php";
use CoffeeCode\Router\Router;
use Http\Middlewares as Middleware;
const BASE = "https://www.localhost/coffeecode/router/exemple/controller";
$router = new Router(BASE);
/**
* routes
*/
$router->namespace("Test");
$router->get("/", "Coffee:home");
$router->get("/edit/{id}", "Coffee:edit", middleware: Middleware::GUEST);
$router->post("/edit/{id}", "Coffee:edit");
$router->get("/logado", "Coffee:logged", middleware: [\Http\Guest::class, \Http\User::class]);
$router->get("/negado", "Coffee:denied", "coffe.denied", Middleware::USER);
/**
* group by routes and namespace
*/
$router->group("admin", \Http\Group::class);
$router->get("/", "Coffee:admin");
$router->get("/user/{id}", "Coffee:admin");
$router->get("/user/{id}/profile", "Coffee:admin", \Http\Guest::class);
$router->get("/user/{id}/profile/{photo}", "Coffee:admin");
/**
* named routes and middlewares
*/
$router->group("name");
$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello", \Http\Guest::class);
$router->get("/params/{category}/page/{page}", "name:params", "name.params");
$router->get("/redirect", "Name:redirect", "name.redirect", Middleware::GUEST);
$router->get("/redirect/{category}/{page}", "name:redirect", "name.redirect.params");
/**
* call route and group middleware
*/
$router->group("call", Middleware::GUEST);
$router->get(
"/",
function ($data, Router $route) {
var_dump($data, $route->current());
echo "<a href='{$route->home()}' title='voltar'>voltar</a>";
}
);
$router->get(
"/{app}/",
function ($data, Router $route) {
var_dump($data, $route->current());
echo "<a href='{$route->home()}' title='voltar'>voltar</a>";
}
);
/**
* Group Error
*/
$router->namespace("Test")->group("error");
$router->get("/{errcode}", "Coffee:notFound");
/**
* execute
*/
$router->dispatch();
if ($router->error()) {
//var_dump($router->error());
$router->redirect("/error/{$router->error()}");
}
================================================
FILE: exemple/spoofing/.htaccess
================================================
RewriteEngine On
Options All -Indexes
# ROUTER URL Rewrite
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=/$1 [L,QSA]
================================================
FILE: exemple/spoofing/index.php
================================================
<?php
require dirname(__DIR__, 2) . "/vendor/autoload.php";
use CoffeeCode\Router\Router;
define("BASE", "https://www.localhost/coffeecode/router/exemple/controller");
$router = new Router(BASE);
/**
* GET httpMethod
*/
$router->get(
"/",
function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>GET :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
}
);
/**
* POST httpMethod
*/
$router->post(
"/",
function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>POST :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
}
);
/**
* PUT spoofing and httpMethod
*/
$router->put(
"/",
function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>PUT :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
}
);
/**
* PATCH spoofing and httpMethod
*/
$router->patch(
"/",
function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>PATCH :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
}
);
/**
* DELETE spoofing and httpMethod
*/
$router->delete(
"/",
function ($data) {
$data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
echo "<h1>DELETE :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
}
);
$router->dispatch();
?>
<form action="" method="POST">
<select name="_method">
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="PATCH">PATCH</option>
<option value="DELETE">DELETE</option>
</select>
<input type="text" name="first_name" value="Robson"/>
<input type="text" name="last_name" value="Leite"/>
<input type="text" name="email" value="cursos@upinside.com.br"/>
<button>CoffeeCode</button>
</form>
================================================
FILE: src/Dispatch.php
================================================
<?php
namespace CoffeeCode\Router;
/**
* Class CoffeeCode Dispatch
*
* @author Robson V. Leite <https://github.com/robsonvleite>
* @package CoffeeCode\Router
*/
abstract class Dispatch
{
use RouterTrait;
/** @var string */
protected string $projectUrl;
/** @var string */
protected string $httpMethod;
/** @var string */
protected string $path;
/** @var array|null */
protected ?array $route = null;
/** @var array */
protected array $routes;
/** @var string */
protected string $separator;
/** @var string|null */
protected ?string $namespace = null;
/** @var string|null */
protected ?string $group = null;
/** @var array|null */
protected ?array $middleware = null;
/** @var array|null */
protected ?array $data = null;
/** @var int */
protected ?int $error = null;
/** @const int Bad Request */
public const BAD_REQUEST = 400;
/** @const int Not Found */
public const NOT_FOUND = 404;
/** @const int Method Not Allowed */
public const METHOD_NOT_ALLOWED = 405;
/** @const int Not Implemented */
public const NOT_IMPLEMENTED = 501;
/**
* Dispatch constructor.
*
* @param string $projectUrl
* @param null|string $separator
*/
public function __construct(string $projectUrl, ?string $separator = ":")
{
$this->projectUrl = (substr($projectUrl, "-1") == "/" ? substr($projectUrl, 0, -1) : $projectUrl);
$this->path = rtrim((filter_input(INPUT_GET, "route", FILTER_DEFAULT) ?? "/"), "/");
$this->separator = ($separator ?? ":");
$this->httpMethod = $_SERVER['REQUEST_METHOD'];
}
/**
* @return array
*/
public function __debugInfo()
{
return $this->routes;
}
/**
* @param string $name
* @param array|null $data
* @return string|null
*/
public function route(string $name, array $data = null): ?string
{
foreach ($this->routes as $http_verb) {
foreach ($http_verb as $route_item) {
if (!empty($route_item["name"]) && $route_item["name"] == $name) {
return $this->treat($route_item, $data);
}
}
}
return null;
}
/**
* @param null|string $namespace
* @return Dispatch
*/
public function namespace(?string $namespace): Dispatch
{
$this->namespace = ($namespace ? ucwords($namespace) : null);
return $this;
}
/**
* @param null|string $group
* @return Dispatch
*/
public function group(?string $group, array|string $middleware = null): Dispatch
{
$this->group = ($group ? trim($group, "/") : null);
$this->middleware = $middleware ? [$this->group => $middleware] : null;
return $this;
}
/**
* @return null|array
*/
public function data(): ?array
{
return $this->data;
}
/**
* @return object|null
*/
public function current(): ?object
{
return (object)array_merge(
[
"namespace" => $this->namespace,
"group" => $this->group,
"path" => $this->path
],
$this->route ?? []
);
}
/**
* @return string
*/
public function home(): string
{
return $this->projectUrl;
}
/**
* @param string $route
* @param array|null $data
*/
public function redirect(string $route, array $data = null): void
{
if ($name = $this->route($route, $data)) {
header("Location: {$name}");
exit;
}
if (filter_var($route, FILTER_VALIDATE_URL)) {
header("Location: {$route}");
exit;
}
$route = (substr($route, 0, 1) == "/" ? $route : "/{$route}");
header("Location: {$this->projectUrl}{$route}");
exit;
}
/**
* @return null|int
*/
public function error(): ?int
{
return $this->error;
}
/**
* @return bool
*/
public function dispatch(): bool
{
if (empty($this->routes) || empty($this->routes[$this->httpMethod])) {
$this->error = self::NOT_IMPLEMENTED;
return false;
}
$this->route = null;
foreach ($this->routes[$this->httpMethod] as $key => $route) {
if (preg_match("~^" . $key . "$~", $this->path, $found)) {
$this->route = $route;
}
}
return $this->execute();
}
}
================================================
FILE: src/Router.php
================================================
<?php
namespace CoffeeCode\Router;
/**
* Class CoffeeCode Router
*
* @author Robson V. Leite <https://github.com/robsonvleite>
* @package CoffeeCode\Router
*/
class Router extends Dispatch
{
/**
* Router constructor.
*
* @param string $projectUrl
* @param null|string $separator
*/
public function __construct(string $projectUrl, ?string $separator = ":")
{
parent::__construct($projectUrl, $separator);
}
/**
* @param string $route
* @param callable|string $handler
* @param string|null $name
* @param array|string|null $middleware
*/
public function get(
string $route,
callable|string $handler,
string $name = null,
array|string $middleware = null
): void {
$this->addRoute("GET", $route, $handler, $name, $middleware);
}
/**
* @param string $route
* @param callable|string $handler
* @param string|null $name
* @param array|string|null $middleware
*/
public function post(
string $route,
callable|string $handler,
string $name = null,
array|string $middleware = null
): void {
$this->addRoute("POST", $route, $handler, $name, $middleware);
}
/**
* @param string $route
* @param callable|string $handler
* @param string|null $name
* @param array|string|null $middleware
*/
public function put(
string $route,
callable|string $handler,
string $name = null,
array|string $middleware = null
): void {
$this->addRoute("PUT", $route, $handler, $name, $middleware);
}
/**
* @param string $route
* @param callable|string $handler
* @param string|null $name
* @param array|string|null $middleware
*/
public function patch(
string $route,
callable|string $handler,
string $name = null,
array|string $middleware = null
): void {
$this->addRoute("PATCH", $route, $handler, $name, $middleware);
}
/**
* @param string $route
* @param callable|string $handler
* @param string|null $name
* @param array|string|null $middleware
*/
public function delete(
string $route,
callable|string $handler,
string $name = null,
array|string $middleware = null
): void {
$this->addRoute("DELETE", $route, $handler, $name, $middleware);
}
}
================================================
FILE: src/RouterTrait.php
================================================
<?php
namespace CoffeeCode\Router;
/**
* Trait RouterTrait
* @package CoffeeCode\Router
*/
trait RouterTrait
{
/**
* @param string $method
* @param string $route
* @param callable|string $handler
* @param string|null $name
* @param array|string|null $middleware
*/
protected function addRoute(
string $method,
string $route,
callable|string $handler,
string $name = null,
array|string $middleware = null
): void {
$route = rtrim($route, "/");
$removeGroupFromPath = $this->group ? str_replace($this->group, "", $this->path) : $this->path;
$pathAssoc = trim($removeGroupFromPath, "/");
$routeAssoc = trim($route, "/");
preg_match_all("~\{\s* ([a-zA-Z_][a-zA-Z0-9_-]*) \}~x", $routeAssoc, $keys, PREG_SET_ORDER);
$routeDiff = array_values(array_diff_assoc(explode("/", $pathAssoc), explode("/", $routeAssoc)));
$this->formSpoofing();
$offset = 0;
foreach ($keys as $key) {
$this->data[$key[1]] = ($routeDiff[$offset++] ?? null);
}
$route = (!$this->group ? $route : "/{$this->group}{$route}");
$data = $this->data;
$namespace = $this->namespace;
$middleware = $middleware ?? (!empty($this->middleware[$this->group]) ? $this->middleware[$this->group] : null);
$router = function () use ($method, $handler, $data, $route, $name, $namespace, $middleware) {
return [
"route" => $route,
"name" => $name,
"method" => $method,
"middlewares" => $middleware,
"handler" => $this->handler($handler, $namespace),
"action" => $this->action($handler),
"data" => $data
];
};
$route = preg_replace('~{([^}]*)}~', "([^/]+)", $route);
$this->routes[$method][$route] = $router();
}
/**
* httpMethod form spoofing
*/
protected function formSpoofing(): void
{
$post = filter_input_array(INPUT_POST, FILTER_DEFAULT);
if (!empty($post['_method']) && in_array($post['_method'], ["PUT", "PATCH", "DELETE"])) {
$this->httpMethod = $post['_method'];
$this->data = $post;
unset($this->data["_method"]);
return;
}
if ($this->httpMethod == "POST") {
$this->data = filter_input_array(INPUT_POST, FILTER_DEFAULT);
unset($this->data["_method"]);
return;
}
if (in_array($this->httpMethod, ["PUT", "PATCH", "DELETE"]) && !empty($_SERVER['CONTENT_LENGTH'])) {
parse_str(file_get_contents('php://input', false, null, 0, $_SERVER['CONTENT_LENGTH']), $putPatch);
$this->data = $putPatch;
unset($this->data["_method"]);
return;
}
$this->data = [];
}
/**
* @return bool
*/
private function execute(): bool
{
if ($this->route) {
if (!$this->middleware()) {
return false;
}
if (is_callable($this->route['handler'])) {
call_user_func($this->route['handler'], ($this->route['data'] ?? []), $this);
return true;
}
$controller = $this->route['handler'];
$method = $this->route['action'];
if (class_exists($controller)) {
$newController = new $controller($this);
if (method_exists($controller, $method)) {
$newController->$method(($this->route['data'] ?? []));
return true;
}
$this->error = self::METHOD_NOT_ALLOWED;
return false;
}
$this->error = self::BAD_REQUEST;
return false;
}
$this->error = self::NOT_FOUND;
return false;
}
/**
* @return bool
*/
private function middleware(): bool
{
if (empty($this->route["middlewares"])) {
return true;
}
$middlewares = is_array(
$this->route["middlewares"]
) ? $this->route["middlewares"] : [$this->route["middlewares"]];
foreach ($middlewares as $middleware) {
if (class_exists($middleware)) {
$newMiddleware = new $middleware;
if (method_exists($newMiddleware, "handle")) {
if (!$newMiddleware->handle($this)) {
return false;
}
} else {
$this->error = self::METHOD_NOT_ALLOWED;
return false;
}
} else {
$this->error = self::NOT_IMPLEMENTED;
return false;
}
}
return true;
}
/**
* @param callable|string $handler
* @param string|null $namespace
* @return callable|string
*/
private function handler(callable|string $handler, ?string $namespace): callable|string
{
return (!is_string($handler) ? $handler : "{$namespace}\\" . explode($this->separator, $handler)[0]);
}
/**
* @param callable|string $handler
* @return string|null
*/
private function action(callable|string $handler): ?string
{
return (!is_string($handler) ?: (explode($this->separator, $handler)[1] ?? null));
}
/**
* @param array $route_item
* @param array|null $data
* @return string|null
*/
private function treat(array $route_item, array $data = null): ?string
{
$route = $route_item["route"];
if (!empty($data)) {
$arguments = [];
$params = [];
foreach ($data as $key => $value) {
if (!strstr($route, "{{$key}}")) {
$params[$key] = $value;
}
$arguments["{{$key}}"] = $value;
}
$route = $this->process($route, $arguments, $params);
}
return "{$this->projectUrl}{$route}";
}
/**
* @param string $route
* @param array $arguments
* @param array|null $params
* @return string
*/
private function process(string $route, array $arguments, array $params = null): string
{
$params = (!empty($params) ? "?" . http_build_query($params) : null);
return str_replace(array_keys($arguments), array_values($arguments), $route) . "{$params}";
}
}
gitextract_3ldu3wt6/
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── composer.json
├── exemple/
│ ├── controller/
│ │ ├── .htaccess
│ │ ├── Http/
│ │ │ ├── Group.php
│ │ │ ├── Guest.php
│ │ │ ├── Middlewares.php
│ │ │ └── User.php
│ │ ├── Test/
│ │ │ ├── Coffee.php
│ │ │ └── Name.php
│ │ └── index.php
│ └── spoofing/
│ ├── .htaccess
│ └── index.php
└── src/
├── Dispatch.php
├── Router.php
└── RouterTrait.php
SYMBOL INDEX (49 symbols across 9 files)
FILE: exemple/controller/Http/Group.php
class Group (line 5) | class Group
method handle (line 7) | public function handle(): bool
FILE: exemple/controller/Http/Guest.php
class Guest (line 5) | class Guest
method handle (line 7) | public function handle(): bool
FILE: exemple/controller/Http/Middlewares.php
class Middlewares (line 5) | class Middlewares
FILE: exemple/controller/Http/User.php
class User (line 7) | class User
method handle (line 9) | public function handle(Router $router): bool
FILE: exemple/controller/Test/Coffee.php
class Coffee (line 11) | class Coffee
method __construct (line 16) | public function __construct(Router $router)
method home (line 50) | public function home(array $data): void
method edit (line 59) | public function edit(array $data): void
method notfound (line 76) | public function notfound(array $data): void
method admin (line 84) | public function admin(array $data): void
method logged (line 92) | public function logged(array $data)
method denied (line 103) | public function denied(array $data)
FILE: exemple/controller/Test/Name.php
class Name (line 7) | class Name
method __construct (line 12) | public function __construct($router)
method home (line 26) | public function home(): void
method hello (line 34) | public function hello(): void
method params (line 40) | public function params(array $data): void
method redirect (line 46) | public function redirect(array $data): void
FILE: src/Dispatch.php
class Dispatch (line 11) | abstract class Dispatch
method __construct (line 66) | public function __construct(string $projectUrl, ?string $separator = ":")
method __debugInfo (line 77) | public function __debugInfo()
method route (line 87) | public function route(string $name, array $data = null): ?string
method namespace (line 103) | public function namespace(?string $namespace): Dispatch
method group (line 113) | public function group(?string $group, array|string $middleware = null)...
method data (line 123) | public function data(): ?array
method current (line 131) | public function current(): ?object
method home (line 146) | public function home(): string
method redirect (line 155) | public function redirect(string $route, array $data = null): void
method error (line 175) | public function error(): ?int
method dispatch (line 183) | public function dispatch(): bool
FILE: src/Router.php
class Router (line 11) | class Router extends Dispatch
method __construct (line 19) | public function __construct(string $projectUrl, ?string $separator = ":")
method get (line 30) | public function get(
method post (line 45) | public function post(
method put (line 60) | public function put(
method patch (line 75) | public function patch(
method delete (line 90) | public function delete(
FILE: src/RouterTrait.php
type RouterTrait (line 9) | trait RouterTrait
method addRoute (line 18) | protected function addRoute(
method formSpoofing (line 63) | protected function formSpoofing(): void
method execute (line 96) | private function execute(): bool
method middleware (line 133) | private function middleware(): bool
method handler (line 168) | private function handler(callable|string $handler, ?string $namespace)...
method action (line 177) | private function action(callable|string $handler): ?string
method treat (line 187) | private function treat(array $route_item, array $data = null): ?string
method process (line 211) | private function process(string $route, array $arguments, array $param...
Condensed preview — 17 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (42K chars).
[
{
"path": "CONTRIBUTING.md",
"chars": 962,
"preview": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nWe accept contributions via Pull Requests"
},
{
"path": "LICENSE",
"chars": 1093,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2018 Robson V. Leite @CoffeeCode\n\nPermission is hereby granted, free of charge, to "
},
{
"path": "README.md",
"chars": 12148,
"preview": "# Router @CoffeeCode\n\n[](h"
},
{
"path": "composer.json",
"chars": 575,
"preview": "{\n \"name\": \"coffeecode/router\",\n \"description\": \"A classic CoffeeCode Router is easy, fast and extremely uncomplicated"
},
{
"path": "exemple/controller/.htaccess",
"chars": 455,
"preview": "RewriteEngine On\nOptions All -Indexes\n\n# ROUTER WWW Redirect.\nRewriteCond %{HTTP_HOST} !^www\\. [NC]\nRewriteRule ^ https:"
},
{
"path": "exemple/controller/Http/Group.php",
"chars": 260,
"preview": "<?php\n\nnamespace Http;\n\nclass Group\n{\n public function handle(): bool\n {\n echo \"<p><i>O middleware <b>Group"
},
{
"path": "exemple/controller/Http/Guest.php",
"chars": 261,
"preview": "<?php\n\nnamespace Http;\n\nclass Guest\n{\n public function handle(): bool\n {\n echo \"<p><i>O middleware <b>Guest"
},
{
"path": "exemple/controller/Http/Middlewares.php",
"chars": 139,
"preview": "<?php\n\nnamespace Http;\n\nclass Middlewares\n{\n const GUEST = Guest::class;\n const USER = User::class;\n CONST GROU"
},
{
"path": "exemple/controller/Http/User.php",
"chars": 487,
"preview": "<?php\n\nnamespace Http;\n\nuse CoffeeCode\\Router\\Router;\n\nclass User\n{\n public function handle(Router $router): bool\n "
},
{
"path": "exemple/controller/Test/Coffee.php",
"chars": 2882,
"preview": "<?php\n\nnamespace Test;\n\nuse CoffeeCode\\Router\\Router;\n\n/**\n * Class Coffee MVC :: CONTROLLER\n * @package Test\n */\nclass "
},
{
"path": "exemple/controller/Test/Name.php",
"chars": 1441,
"preview": "<?php\n\nnamespace Test;\n\nuse CoffeeCode\\Router\\Router;\n\nclass Name\n{\n /** @var Router */\n private Router $router;\n\n"
},
{
"path": "exemple/controller/index.php",
"chars": 2323,
"preview": "<?php\n\nrequire dirname(__DIR__, 2) . \"/vendor/autoload.php\";\nrequire __DIR__ . \"/Test/Coffee.php\";\nrequire __DIR__ . \"/T"
},
{
"path": "exemple/spoofing/.htaccess",
"chars": 176,
"preview": "RewriteEngine On\nOptions All -Indexes\n\n# ROUTER URL Rewrite\nRewriteCond %{SCRIPT_FILENAME} !-f\nRewriteCond %{SCRIPT_FILE"
},
{
"path": "exemple/spoofing/index.php",
"chars": 1915,
"preview": "<?php\n\nrequire dirname(__DIR__, 2) . \"/vendor/autoload.php\";\n\nuse CoffeeCode\\Router\\Router;\n\ndefine(\"BASE\", \"https://www"
},
{
"path": "src/Dispatch.php",
"chars": 4627,
"preview": "<?php\n\nnamespace CoffeeCode\\Router;\n\n/**\n * Class CoffeeCode Dispatch\n *\n * @author Robson V. Leite <https://github.com/"
},
{
"path": "src/Router.php",
"chars": 2480,
"preview": "<?php\n\nnamespace CoffeeCode\\Router;\n\n/**\n * Class CoffeeCode Router\n *\n * @author Robson V. Leite <https://github.com/ro"
},
{
"path": "src/RouterTrait.php",
"chars": 6552,
"preview": "<?php\n\nnamespace CoffeeCode\\Router;\n\n/**\n * Trait RouterTrait\n * @package CoffeeCode\\Router\n */\ntrait RouterTrait\n{\n "
}
]
About this extraction
This page contains the full source code of the robsonvleite/router GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 17 files (37.9 KB), approximately 10.5k tokens, and a symbol index with 49 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.