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 [![Maintainer](http://img.shields.io/badge/maintainer-@robsonvleite-blue.svg?style=flat-square)](https://twitter.com/robsonvleite) [![Source Code](http://img.shields.io/badge/source-coffeecode/router-blue.svg?style=flat-square)](https://github.com/robsonvleite/router) [![PHP from Packagist](https://img.shields.io/packagist/php-v/coffeecode/router.svg?style=flat-square)](https://packagist.org/packages/coffeecode/router) [![Latest Version](https://img.shields.io/github/release/robsonvleite/router.svg?style=flat-square)](https://github.com/robsonvleite/router/releases) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) [![Quality Score](https://img.shields.io/scrutinizer/g/robsonvleite/router.svg?style=flat-square)](https://scrutinizer-ci.com/g/robsonvleite/router) [![Total Downloads](https://img.shields.io/packagist/dt/coffeecode/router.svg?style=flat-square)](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 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 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 router = $router; } public function home(): void { echo "

Home

"; echo "

", $this->router->route("name.home"), "

"; echo "

", $this->router->route("name.hello"), "

"; echo "

", $this->router->route("name.redirect"), "

"; } public function redirect(): void { $this->router->redirect("name.hello"); } } ``` ###### Named Params ````php 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 get("/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

GET :: Spoofing

", "
", print_r($data, true), "
"; }); /** * GET httpMethod and Route */ $router->get("/", function ($data, Router $route) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

GET :: Spoofing

", "
", print_r($data, true), "
"; var_dump($route->current()); }); /** * POST httpMethod */ $router->post("/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

POST :: Spoofing

", "
", print_r($data, true), "
"; }); /** * PUT spoofing and httpMethod */ $router->put("/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

PUT :: Spoofing

", "
", print_r($data, true), "
"; }); /** * PATCH spoofing and httpMethod */ $router->patch("/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

PATCH :: Spoofing

", "
", print_r($data, true), "
"; }); /** * DELETE spoofing and httpMethod */ $router->delete("/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

DELETE :: Spoofing

", "
", print_r($data, true), "
"; }); $router->dispatch(); ``` ##### Simple Middleware ```php 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 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 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
``` ##### PHP cURL example ```php "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 ================================================ O middleware Group foi executado!

"; $group = true; if ($group) { return true; } return false; } } ================================================ FILE: exemple/controller/Http/Guest.php ================================================ O middleware Guest foi executado!

"; $guest = true; if ($guest) { return true; } return false; } } ================================================ FILE: exemple/controller/Http/Middlewares.php ================================================ O middleware User foi executado!

"; $user = filter_input(INPUT_GET, "user", FILTER_VALIDATE_BOOL); if ($user) { return true; } echo "

Acces Denied!

"; echo "Simular Usuário"; return false; } } ================================================ FILE: exemple/controller/Test/Coffee.php ================================================ Router @CoffeeCode"; echo "

Normal routes:

"; echo ""; echo "

Group routes:

"; echo ""; echo "

Named and call routes:

"; echo ""; } /** * @param array $data */ public function home(array $data): void { echo "

", __METHOD__, "::", $_SERVER["REQUEST_METHOD"], "


"; echo "
", print_r($data, true), "
"; } /** * @param array $data */ public function edit(array $data): void { echo "

", __METHOD__, "::", $_SERVER["REQUEST_METHOD"], "


"; echo "
"; echo "
", print_r($data, true), "
"; } /** * @param array $data */ public function notfound(array $data): void { echo "

Whoops!

", "
", print_r($data, true), "
"; } /** * @param array $data */ public function admin(array $data): void { echo "

Admin Group:

", "
", print_r($data, true), "
"; } /** * @param array $data */ public function logged(array $data) { echo "

Logged

", "

Essa tela simula execução de múltiplos middlewares

", "
", print_r(
            $data,
            true
        ), "
"; } /** * @param array $data */ public function denied(array $data) { echo "

Acessou com sucesso: (Access Denied)

", "
", print_r($data, true), "
"; } } ================================================ FILE: exemple/controller/Test/Name.php ================================================ router = $router; $params = ["category" => 23213, "page" => 2]; echo "

Named routes:

"; echo ""; } public function home(): void { echo "

Home

"; echo "

", $this->router->route("name.home"), "

"; echo "

", $this->router->route("name.hello"), "

"; echo "

", $this->router->route("name.redirect"), "

"; } public function hello(): void { echo "

Hello World

"; echo "Route Params"; } public function params(array $data): void { echo "

Params

"; 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 ================================================ 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 "voltar"; } ); $router->get( "/{app}/", function ($data, Router $route) { var_dump($data, $route->current()); echo "voltar"; } ); /** * 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 ================================================ get( "/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

GET :: Spoofing

", "
", print_r($data, true), "
"; } ); /** * POST httpMethod */ $router->post( "/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

POST :: Spoofing

", "
", print_r($data, true), "
"; } ); /** * PUT spoofing and httpMethod */ $router->put( "/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

PUT :: Spoofing

", "
", print_r($data, true), "
"; } ); /** * PATCH spoofing and httpMethod */ $router->patch( "/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

PATCH :: Spoofing

", "
", print_r($data, true), "
"; } ); /** * DELETE spoofing and httpMethod */ $router->delete( "/", function ($data) { $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data; echo "

DELETE :: Spoofing

", "
", print_r($data, true), "
"; } ); $router->dispatch(); ?>
================================================ FILE: src/Dispatch.php ================================================ * @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 ================================================ * @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 ================================================ 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}"; } }