Core/src/Router/Router.php

79 lines
1.7 KiB
PHP
Raw Normal View History

2020-06-12 13:57:36 +00:00
<?php
namespace Benzine\Router;
use Slim\App;
use Monolog\Logger;
class Router
{
protected static $instance;
/** @var Route[] */
protected $routes = [];
/** @var Logger */
protected $logger;
/**
* @return Router
*/
public static function Instance()
{
if (!self::$instance instanceof Router) {
self::$instance = new Router();
}
return self::$instance;
}
public function weighRoutes(): Router
{
$allocatedRoutes = [];
if (is_array($this->routes) && count($this->routes) > 0) {
uasort($this->routes, function (Route $a, Route $b) {
return $a->getWeight() > $b->getWeight();
});
foreach ($this->routes as $index => $route) {
if (!isset($allocatedRoutes[$route->getHttpMethod().$route->getRouterPattern()])) {
$allocatedRoutes[$route->getHttpMethod().$route->getRouterPattern()] = true;
} else {
unset($this->routes[$index]);
}
}
}
return $this;
}
public function populateRoutes(App $app)
{
$this->weighRoutes();
if (count($this->routes) > 0) {
foreach ($this->routes as $route) {
$app = $route->populateRoute($app);
}
}
return $app;
}
public function addRoute(Route $route)
{
$this->routes[$route->getUniqueIdentifier()] = $route;
return $this;
}
/**
* @return Route[]
*/
public function getRoutes()
{
ksort($this->routes);
return $this->routes;
}
}