Now there is a group method. Things can be defined for the whole group, like middlewares

This commit is contained in:
2019-08-26 18:20:57 -04:00
parent 8cb3178709
commit 9a57084294
4 changed files with 201 additions and 128 deletions
+21
View File
@@ -0,0 +1,21 @@
<?php
include_once('src/Routes/Route.php');
include_once('src/Routes/RouteGroup.php');
include_once('src/Routes/RouteCollection.php');
RouteCollection::group('/base', function(){
RouteCollection::get('/', function(){ echo 'Eu sou a raiz dento da base'; });
RouteCollection::get('/aaa', function(){ echo 'Eu sou a aaa dentro da base'; });
})->doBlock()->middlewareAdd('login-required')->notBlock();
//RouteCollection::get('/', function(){ echo 'Eu sou a raiz'; });
RouteCollection::get('/aaa', function(){ echo 'Eu sou aaaaa'; })->doBlock()->middlewareIgnore('auth')->middlewareAdd('aaaa');
echo '<pre>';
foreach(RouteCollection::getInstance()->_routes as $route){
var_dump($route);
echo '<hr />';
}
RouteCollection::getInstance()->submit();
+27 -26
View File
@@ -31,7 +31,7 @@ class Route {
/* /*
* URI Segments * URI Segments
*/ */
public $_uri_segments = Array(); public $_uriSegments = Array();
/* /*
* Extracted params * Extracted params
@@ -71,7 +71,7 @@ class Route {
/* /*
* Is there a problem witch one? * Is there a problem witch one?
*/ */
public $_http_error = false; public $_httpError = false;
/* /*
* This rout should be counted? * This rout should be counted?
@@ -81,12 +81,12 @@ class Route {
/* /*
* Middlewares to remove from the list * Middlewares to remove from the list
*/ */
public $_middlewares_to_ignore = Array(); public $_middlewaresToIgnore = Array();
/* /*
* From Klein * From Klein
* HTTP status List * HTTP status List
*/ */
protected static $http_messages = array( protected static $httpMessages = array(
// Informational 1xx // Informational 1xx
100 => 'Continue', 100 => 'Continue',
101 => 'Switching Protocols', 101 => 'Switching Protocols',
@@ -138,7 +138,7 @@ class Route {
//======================================================= //=======================================================
function execute() { function execute() {
foreach ($this->_before as $key => $before) { foreach ($this->_before as $key => $before) {
if (!in_array($key, $this->_middlewares_to_ignore) && !$this->_ignore) { if (!in_array($key, $this->_middlewaresToIgnore) && !$this->_ignore) {
call_user_func($before); call_user_func($before);
} }
} }
@@ -198,73 +198,74 @@ class Route {
$this->_regex = "/\/" . $this->_regex . "$/"; $this->_regex = "/\/" . $this->_regex . "$/";
} }
function create_indexes() { function createIndexes() {
foreach ($this->_segments as $key => $segment) { foreach ($this->_segments as $key => $segment) {
if (preg_match('/\[.*?\]$/', $segment)) { if (preg_match('/\[.*?\]$/', $segment)) {
$segment = trim(trim($segment, '['), ']'); $segment = trim(trim($segment, '['), ']');
$param = explode(':', $segment); $param = explode(':', $segment);
$this->_params[$param[1]] = $this->_uri_segments[$key]; $this->_params[$param[1]] = $this->_uriSegments[$key];
} }
} }
} }
function set_uri($uri) { function setUri($uri) {
$this->_uri = $uri; $this->_uri = $uri;
return $this; return $this;
} }
function get_segments() { function getSegments() {
return $this->_segments; return $this->_segments;
} }
function do_block() { function doBlock() {
$this->_block = true; $this->_block = true;
return $this; return $this;
} }
function not_block() { function notBlock() {
$this->_block = false; $this->_block = false;
return $this; return $this;
} }
function do_ignore() { function doIgnore() {
$this->_ignore = true; $this->_ignore = true;
return $this; return $this;
} }
function not_ignore() { function notIgnore() {
$this->_ignore = false; $this->_ignore = false;
return $this; return $this;
} }
function middleware_ignore($name = '') { function middlewareIgnore($name = '') {
$this->_middlewares_to_ignore[] = $name; $this->_middlewaresToIgnore[] = $name;
return $this; return $this;
} }
function middleware_add($name = '') { function middlewareAdd($name = '') {
$this->_before[$name] = $function;
return $this;
}
function middlewareAppend($name = '', $function) {
$this->_before[$name] = $function; $this->_before[$name] = $function;
} }
function middleware_append($name = '', $function) { function setWeight($weigth = 0) {
$this->_before[$name] = $function;
}
function set_weight($weigth = 0) {
$this->_weight = $weigth; $this->_weight = $weigth;
return $this; return $this;
} }
function set_http_error($code = 400, $message = null) { function setHttpError($code = 400, $message = null) {
if ($message == null) { if ($message == null) {
$message = self::$http_messages[$code]; $message = self::$httpMessages[$code];
} }
$info = new \stdClass(); $info = new \stdClass();
$info->code = $code; $info->code = $code;
$info->message = $message; $info->message = $message;
$this->_http_error = $info; $this->_httpError = $info;
return $this; return $this;
} }
@@ -275,8 +276,8 @@ class Route {
} }
if (preg_match($this->_regex, $uri)) { if (preg_match($this->_regex, $uri)) {
$this->_uri_segments = explode('/', $uri); $this->_uriSegments = explode('/', $uri);
$this->create_indexes(); $this->createIndexes();
return true; return true;
} }
+61 -99
View File
@@ -4,16 +4,22 @@ namespace Routes;
class RouteCollection { class RouteCollection {
private static $_route_collection; private static $_routeCollection;
public $_uri = '/'; public $_uri = '/';
public $_routes = Array(); public $_routes = Array();
private $_verb = ''; private $_verb = '';
private $_loaded_files = Array(); private $_loadedFiles = Array();
private $_errors = Array(); private $_errors = Array();
private $_default_middlewares = Array(); private $_defaultMiddlewares = Array();
private $_middleware_set = Array(); private $_middlewareSet = Array();
private static $_verbs_whitelist = Array('*', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'CLI'); private static $_verbsWhitelist = Array('*', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'CLI');
private static $_verbs_web = Array('GET', 'POST', 'PUT', 'PATCH', 'DELETE'); private static $_verbsWeb = Array('GET', 'POST', 'PUT', 'PATCH', 'DELETE');
public $_groupIn = false;
public $_groupBase = '';
public $_groupList = [];
//SINGLETON============================================== //SINGLETON==============================================
@@ -22,26 +28,26 @@ class RouteCollection {
} }
private static function newObj() { private static function newObj() {
if (!isset(self::$_route_collection)) { if (!isset(self::$_routeCollection)) {
self::$_route_collection = new RouteCollection(); self::$_routeCollection = new RouteCollection();
if (php_sapi_name() == "cli") { if (php_sapi_name() == "cli") {
self::$_route_collection->_uri = isset($_SERVER['argv'][1]) ? '/' . $_SERVER['argv'][1] : '/'; self::$_routeCollection->_uri = isset($_SERVER['argv'][1]) ? '/' . $_SERVER['argv'][1] : '/';
} else { } else {
self::$_route_collection->_uri = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI'])[0] : '/'; self::$_routeCollection->_uri = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI'])[0] : '/';
} }
self::$_route_collection->define_verb(); self::$_routeCollection->defineVerb();
} }
return self::$_route_collection; return self::$_routeCollection;
} }
/** /**
* *
*/ */
public static function getInstance() { public static function getInstance() {
if (!isset(self::$_route_collection)) { if (!isset(self::$_routeCollection)) {
return self::newObj(); return self::newObj();
} }
return self::$_route_collection; return self::$_routeCollection;
} }
//HELPERS================================================ //HELPERS================================================
@@ -57,7 +63,7 @@ class RouteCollection {
foreach (new \RecursiveIteratorIterator($rdi) as $file) { foreach (new \RecursiveIteratorIterator($rdi) as $file) {
foreach ($filenames as $filename) { foreach ($filenames as $filename) {
if (strpos($file, $filename)) { if (strpos($file, $filename)) {
$instance->_loaded_files[] = $file; $instance->_loadedFiles[] = $file;
} }
} }
} }
@@ -68,11 +74,11 @@ class RouteCollection {
* *
* Load the files with the routes * Load the files with the routes
*/ */
function load_routes() { function loadRoutes() {
$instance = self::getInstance(); $instance = self::getInstance();
foreach ($instance->_loaded_files as $loaded_file) { foreach ($instance->_loadedFiles as $loadedFile) {
include $loaded_file; include $loadedFile;
} }
return $instance; return $instance;
} }
@@ -82,7 +88,7 @@ class RouteCollection {
* GET | POST | PUT | PATCH | DELETE | CLI * GET | POST | PUT | PATCH | DELETE | CLI
* *
*/ */
private function define_verb() { private function defineVerb() {
$verb = ''; $verb = '';
@@ -94,7 +100,7 @@ class RouteCollection {
$verb = strtoupper($_SERVER['REQUEST_METHOD']); $verb = strtoupper($_SERVER['REQUEST_METHOD']);
} }
if (in_array($verb, self::$_verbs_whitelist)) { if (in_array($verb, self::$_verbsWhitelist)) {
$this->_verb = $verb; $this->_verb = $verb;
} else { } else {
echo 'Invalid Verb'; echo 'Invalid Verb';
@@ -119,26 +125,26 @@ class RouteCollection {
function submit() { function submit() {
global $ROUTE; global $ROUTE;
self::$_route_collection->sort_routes(); self::$_routeCollection->sort_routes();
$one_hit = false; $one_hit = false;
foreach (self::$_route_collection->_routes as $route) { foreach (self::$_routeCollection->_routes as $route) {
if (!in_array(self::$_route_collection->_verb, $route->_verb) && !in_array('*', $route->_verb)) { if (!in_array(self::$_routeCollection->_verb, $route->_verb) && !in_array('*', $route->_verb)) {
//No it is not //No it is not
continue; continue;
} }
//Request match a route //Request match a route
$match = $route->match(self::$_route_collection->_uri); $match = $route->match(self::$_routeCollection->_uri);
if ($match) { if ($match) {
//Yup. Execute the route //Yup. Execute the route
$ROUTE = $route; $ROUTE = $route;
$route->_before = $this->_default_middlewares; $route->_before = $this->_defaultMiddlewares;
$route->execute(); $route->execute();
@@ -146,8 +152,8 @@ class RouteCollection {
$one_hit = true; $one_hit = true;
} }
if ($route->_http_error) { if ($route->_httpError) {
$this->http_error($route->_http_error); $this->httpError($route->_httpError);
return; return;
} }
@@ -162,112 +168,63 @@ class RouteCollection {
$info = new \stdClass(); $info = new \stdClass();
$info->code = 404; $info->code = 404;
$info->message = 'Not Found'; $info->message = 'Not Found';
self::$_route_collection->http_error($info); self::$_routeCollection->httpError($info);
} }
} }
static function group($base = '', $callback){
$collection = self::getInstance();
$collection->_groupList = [];
$collection->_groupIn = true;
$collection->_groupBase = $base;
call_user_func($callback);
$collection->_groupBase = '';
$collection->_groupIn = false;
return new RouteGroup($collection->_groupList);
}
//DEFINITORS============================================= //DEFINITORS=============================================
/** /**
* *
*/ */
static function get($uri, $callback, $weight = 0) { static function get($uri, $callback, $weight = 0) {
$route = new Route(); return self::add('GET', $uri, $callback, $weight);
$route->_verb[] = 'GET';
$route->_uri = $uri;
$route->_callback[] = $callback;
$route->_weight = $weight;
$route->prepare();
self::getInstance()->_routes[] = $route;
return $route;
} }
/** /**
* *
*/ */
static function cli($uri, $callback, $weight = 0) { static function cli($uri, $callback, $weight = 0) {
$route = new Route(); return self::add('CLI', $uri, $callback, $weight);
$route->_verb[] = 'CLI';
$route->_uri = $uri;
$route->_callback[] = $callback;
$route->_weight = $weight;
$route->prepare();
self::getInstance()->_routes[] = $route;
return $route;
} }
/** /**
* *
*/ */
static function post($uri, $callback, $weight = 0) { static function post($uri, $callback, $weight = 0) {
$route = new Route(); return self::add('POST', $uri, $callback, $weight);
$route->_verb[] = 'POST';
$route->_uri = $uri;
$route->_callback[] = $callback;
$route->_weight = $weight;
$route->prepare();
self::getInstance()->_routes[] = $route;
return $route;
} }
/** /**
* *
*/ */
static function put($uri, $callback, $weight = 0) { static function put($uri, $callback, $weight = 0) {
$route = new Route(); return self::add('PUT', $uri, $callback, $weight);
$route->_verb[] = 'PUT';
$route->_uri = $uri;
$route->_callback[] = $callback;
$route->_weight = $weight;
$route->prepare();
self::getInstance()->_routes[] = $route;
return $route;
} }
/** /**
* *
*/ */
static function patch($uri, $callback, $weight = 0) { static function patch($uri, $callback, $weight = 0) {
$route = new Route(); return self::add('PATCH', $uri, $callback, $weight);
$route->_verb[] = 'PATCH';
$route->_uri = $uri;
$route->_callback[] = $callback;
$route->_weight = $weight;
$route->prepare();
self::getInstance()->_routes[] = $route;
return $route;
} }
/** /**
* *
*/ */
static function delete($uri, $callback, $weight = 0) { static function delete($uri, $callback, $weight = 0) {
$route = new Route(); return self::add('DELETE', $uri, $callback, $weight);
$route->_verb[] = 'DELETE';
$route->_uri = $uri;
$route->_callback[] = $callback;
$route->_weight = $weight;
$route->prepare();
self::getInstance()->_routes[] = $route;
return $route;
} }
static function resource($uri) { static function resource($uri) {
@@ -280,10 +237,15 @@ class RouteCollection {
static function add($verb, $uri, $callback, $weight = 0) { static function add($verb, $uri, $callback, $weight = 0) {
$route = new Route(); $route = new Route();
if(self::getInstance()->_groupIn){
$uri = self::getInstance()->_groupBase . $uri;
self::getInstance()->_groupList[] = &$route;
}
$uri = rtrim($uri, '/');
if (is_array($verb)) { if (is_array($verb)) {
$route->_verb = array_map('strtoupper', $verb); $route->_verb = array_map('strtoupper', $verb);
} else if (strtoupper($verb) == 'WEB') { } else if (strtoupper($verb) == 'WEB') {
$route->_verb[] = self::_verbs_web; $route->_verb[] = self::_verbsWeb;
} else { } else {
$route->_verb[] = strtoupper($verb); $route->_verb[] = strtoupper($verb);
} }
@@ -309,20 +271,20 @@ class RouteCollection {
* *
*/ */
static function addDefaultMiddleware($name = '', $function) { static function addDefaultMiddleware($name = '', $function) {
self::getInstance()->_default_middlewares[$name] = $function; self::getInstance()->_defaultMiddlewares[$name] = $function;
} }
/** /**
* *
*/ */
static function registerMiddleware($name = '', $function) { static function registerMiddleware($name = '', $function) {
self::getInstance()->_middleware_set[$name] = $function; self::getInstance()->_middlewareSet[$name] = $function;
} }
/** /**
* *
*/ */
static function on_http_error($function) { static function onHttpError($function) {
$instance = self::getInstance(); $instance = self::getInstance();
$instance->_errors[] = $function; $instance->_errors[] = $function;
} }
@@ -330,7 +292,7 @@ class RouteCollection {
/** /**
* *
*/ */
private function http_error(\stdClass $info) { private function httpError(\stdClass $info) {
$info = (array) $info; $info = (array) $info;
foreach ($this->_errors as $error) { foreach ($this->_errors as $error) {
call_user_func_array($error, $info); call_user_func_array($error, $info);
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace Routes;
class RouteGroup{
private $_routeGroup = [];
function __construct($group){
$this->setGroup($group);
}
function setGroup($group){
$this->_routeGroup = $group;
}
function doBlock() {
foreach($this->_routeGroup as $route){
$route->_block = true;
}
return $this;
}
function notBlock() {
foreach($this->_routeGroup as $route){
$route->_block = false;
}
return $this;
}
function doIgnore() {
foreach($this->_routeGroup as $route){
$route->_ignore = true;
}
return $this;
}
function notIgnore() {
foreach($this->_routeGroup as $route){
$route->_ignore = false;
}
return $this;
}
function middlewareIgnore($name = '') {
foreach($this->_routeGroup as $route){
$route->_middlewaresToIgnore[] = $name;
}
return $this;
}
function middlewareAdd($name = '') {
foreach($this->_routeGroup as $route){
$route->_before[$name] = $function;
}
return $this;
}
function middlewareAppend($name = '', $function) {
foreach($this->_routeGroup as $route){
$route->_before[$name] = $function;
}
return $this;
}
function setWeight($weigth = 0) {
foreach($this->_routeGroup as $route){
$route->_weight = $weigth;
}
return $this;
}
function setHttpError($code = 400, $message = null) {
foreach($this->_routeGroup as $route){
if ($message == null) {
$message = self::$httpMessages[$code];
}
$info = new \stdClass();
$info->code = $code;
$info->message = $message;
$route->_httpError = $info;
}
return $this;
}
}