Created
August 7, 2016 02:43
-
-
Save jm42/b4a2a6a9daa23d042edf6d3eb25ea27b to your computer and use it in GitHub Desktop.
Router idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class R { | |
protected $matchers = []; | |
function __invoke(...$matchers) { | |
$uniq = uniqid(); | |
$this->matchers[$uniq] = $matchers; | |
return $uniq; | |
} | |
function match($req) { | |
$resolver = function($args, $matcher) use($req) { | |
if (($match = $matcher($req)) !== false) { | |
return ($args ?: []) + (is_array($match) ? $match : []); | |
} | |
return false; | |
}; | |
foreach ($this->matchers as $name => $matchers) { | |
if (($match = array_reduce($matchers, $resolver, false)) !== false) { | |
return [$name, $match]; | |
} | |
} | |
return false; | |
} | |
} | |
function m($m) { | |
return function($req) use($m) { | |
return $req['method'] === $m; | |
}; | |
} | |
$r = new R; | |
$m = [$r(m('GET')) => function($a) { return "Hello"; }]; | |
list($n, $a) = $r->match(['method' => 'GET', 'path' => '/']); | |
var_dump($m[$n]($a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment