99 lines
1.9 KiB
PHP
Executable File
99 lines
1.9 KiB
PHP
Executable File
<?php
|
|
|
|
class Route {
|
|
public $method = "GET";
|
|
public $pattern = "";
|
|
public $function = null;
|
|
public $auth = false;
|
|
public $args = [];
|
|
|
|
function __construct($m, $p, $f, $a = false) {
|
|
$this->method = $m;
|
|
$this->pattern = $p;
|
|
$this->function = $f;
|
|
$this->auth = $a;
|
|
}
|
|
|
|
function matches($m, $path) {
|
|
|
|
if ($this->auth != false) {
|
|
|
|
if ($this->auth instanceof \Closure) {
|
|
if (!$this->auth->call($this)) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
if (is_array($this->auth)) {
|
|
$c = $this->auth[0];
|
|
$f = $this->auth[1];
|
|
if (!$c::$f()) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
if (strtolower($m) != strtolower($this->method)) return false;
|
|
$src_parts = explode("/", $path);
|
|
$dst_parts = explode("/", $this->pattern);
|
|
|
|
if (count($src_parts) != count($dst_parts)) {
|
|
return false;
|
|
}
|
|
|
|
$this->args = [];
|
|
for ($i = 0; $i < count($src_parts); $i++) {
|
|
$sp = $src_parts[$i];
|
|
$dp = $dst_parts[$i];
|
|
if (preg_match('/^{(.*)}$/', $dp, $m)) {
|
|
$this->args[$m[1]] = $sp;
|
|
continue;
|
|
}
|
|
if ($sp != $dp) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function get_args() {
|
|
return $this->args;
|
|
}
|
|
|
|
function call($req) {
|
|
if ($this->function instanceof \Closure) {
|
|
|
|
// $fargs = func_get_args($this->function);
|
|
// if (in_array("_request", $fargs)) {
|
|
// $this->args["_request"] = $req;
|
|
// }
|
|
|
|
$ref = new ReflectionFunction($this->function);
|
|
foreach ($ref->getParameters() as $arg) {
|
|
if ($arg->name == "_request") {
|
|
$this->args["_request"] = $req;
|
|
}
|
|
}
|
|
|
|
return $this->function->call($this, ...$this->args);
|
|
}
|
|
|
|
if (is_array($this->function)) {
|
|
$c = $this->function[0];
|
|
$f = $this->function[1];
|
|
$ref = new ReflectionMethod($c, $f);
|
|
foreach ($ref->getParameters() as $arg) {
|
|
if ($arg->name == "_request") {
|
|
$this->args["_request"] = $req;
|
|
}
|
|
}
|
|
|
|
|
|
return $c::$f(...$this->args);
|
|
}
|
|
|
|
return [404, "Not Found"];
|
|
}
|
|
}
|