Skip to content

Commit

Permalink
Router::configure now uses Configure2Trait and can read from director…
Browse files Browse the repository at this point in the history
…y and files and support 'sort'
  • Loading branch information
mosbth committed Sep 26, 2017
1 parent 7385cb4 commit affc134
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
6 changes: 6 additions & 0 deletions REVISION.md
Expand Up @@ -14,6 +14,12 @@ Notes for development v1.1.0*
* (Use regexp to match route).


v1.0.14 (2017-09-26)
---------------------------------

* Router::configure now uses Configure2Trait and can read from directory and files and support "sort".


v1.0.13 (2017-09-14)
---------------------------------

Expand Down
50 changes: 40 additions & 10 deletions src/Route/Router.php
Expand Up @@ -5,7 +5,7 @@
use Anax\DI\InjectionAwareInterface;
use Anax\DI\InjectionAwareTrait;
use \Anax\Configure\ConfigureInterface;
use \Anax\Configure\ConfigureTrait;
use \Anax\Configure\Configure2Trait;

/**
* A container for routes.
Expand All @@ -15,8 +15,8 @@ class Router implements
ConfigureInterface
{
use InjectionAwareTrait;
use ConfigureTrait {
configure as protected loadConfiguration;
use Configure2Trait {
configure as protected configure2;
}


Expand All @@ -43,12 +43,30 @@ class Router implements
*/
public function configure($what)
{
$this->loadConfiguration($what);

$this->configure2($what);
$includes = $this->getConfig("routeFiles", []);
foreach ($includes as $include) {
$this->load($include);
$items = $this->getConfig("items", []);
$config = array_merge($includes, $items);

// Add a sort field if missing, to maintain order
// when sorting
$sort = 1;
array_walk($config, function(&$item) use(&$sort) {
$item["sort"] = (isset($item["sort"]))
? $item["sort"]
: $sort++;
});
uasort($config, function($item1, $item2) {
if ($item1["sort"] === $item2["sort"]) {
return 0;
}
return ($item1["sort"] < $item2["sort"]) ? -1 : 1;
});

foreach ($config as $route) {
$this->load($route);
}

return $this;
}

Expand Down Expand Up @@ -128,10 +146,21 @@ public function handleInternal($rule)
public function load($route)
{
$mount = isset($route["mount"]) ? rtrim($route["mount"], "/") : null;
$file = $route["file"];
if (!array_key_exists("mount", $route)) {
// To fix compatibility with new configuration
// where configuration item needs "mount" to be
// used and not ignored.
return $this;
}

$config = $route;
$file = isset($route["file"]) ? $route["file"] : null;
if ($file && is_readable($file)) {
$config = require($file);
}

$config = require($file);
foreach ($config["routes"] as $route) {
$routes = isset($config["routes"]) ? $config["routes"] : [];
foreach ($routes as $route) {
$path = isset($mount)
? $mount . "/" . $route["path"]
: $route["path"];
Expand All @@ -148,6 +177,7 @@ public function load($route)
$route["info"]
);
}

return $this;
}

Expand Down

0 comments on commit affc134

Please sign in to comment.