Files
kiri-core/HttpServer/Route/Router.php
T

556 lines
11 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
namespace HttpServer\Route;
use Closure;
use Exception;
use HttpServer\Http\Context;
2020-09-07 10:51:23 +08:00
use HttpServer\Http\Request;
2020-08-31 01:27:08 +08:00
use HttpServer\IInterface\RouterInterface;
use HttpServer\Application;
2020-08-31 22:33:50 +08:00
use HttpServer\Route\Annotation\Annotation;
2020-09-04 01:05:33 +08:00
use Snowflake\Abstracts\Config;
2020-08-31 01:27:08 +08:00
use Snowflake\Core\JSON;
use Snowflake\Exception\ConfigException;
2020-08-31 12:38:32 +08:00
use Snowflake\Snowflake;
2020-08-31 01:27:08 +08:00
/**
* Class Router
2020-08-31 12:38:32 +08:00
* @package Snowflake\Snowflake\Route
2020-08-31 01:27:08 +08:00
*/
class Router extends Application implements RouterInterface
{
/** @var Node[] $nodes */
public $nodes = [];
public $groupTacks = [];
2020-08-31 22:49:53 +08:00
public $dir = 'App\\Http\\Controllers';
2020-08-31 01:27:08 +08:00
/** @var string[] */
public $methods = ['get', 'post', 'options', 'put', 'delete', 'receive'];
/**
* @throws ConfigException
* 初始化函数路径
*/
public function init()
{
2020-08-31 17:21:45 +08:00
$this->dir = Config::get('http.namespace', false, $this->dir);
2020-08-31 01:27:08 +08:00
}
/**
* @param $path
* @param $handler
* @param string $method
* @return mixed|Node|null
* @throws
*/
public function addRoute($path, $handler, $method = 'any')
{
2020-09-04 18:47:22 +08:00
if (!isset($this->nodes[$method])) {
$this->nodes[$method] = [];
2020-08-31 01:27:08 +08:00
}
2020-09-07 10:42:10 +08:00
// list($first, $explode) = $this->split($path);
$paths = array_column($this->groupTacks, 'prefix');
2020-09-07 10:50:15 +08:00
if (empty($paths)) {
$path = ltrim($path, '/');
} else {
if ($path !== '/') {
$path = implode('/', $paths) . '/' . ltrim($path, '/');
} else {
$path = implode('/', $paths);
}
}
if (empty($path)) {
$path = '/';
}
2020-09-07 10:42:10 +08:00
// $parent = $this->nodes[$method][$first] ?? null;
$this->nodes[$method][$path] = $this->NodeInstance($path, 0, $method);
// if (empty($parent)) {
// $parent = $this->NodeInstance($first, 0, $method);
// $this->nodes[$method][$first] = $parent;
// }
// if ($first !== '/') {
// $parent = $this->bindNode($parent, $explode, $method);
// }
return $this->nodes[$method][$path]->bindHandler($handler);
2020-08-31 01:27:08 +08:00
}
/**
* @param Node $parent
* @param array $explode
* @param $method
* @return Node
*/
private function bindNode($parent, $explode, $method)
{
$a = 0;
if (empty($explode)) {
return $parent->addChild($this->NodeInstance('/', $a, $method), '/');
}
foreach ($explode as $value) {
if (empty($value)) {
continue;
}
++$a;
$search = $parent->findNode($value);
if ($search === null) {
$parent = $parent->addChild($this->NodeInstance($value, $a, $method), $value);
} else {
$parent = $search;
}
}
return $parent;
}
/**
* @param $route
* @param $handler
* @return Node|mixed|null
*/
public function socket($route, $handler)
{
return $this->addRoute($route, $handler, 'socket');
}
/**
* @param $route
* @param $handler
* @return mixed|Node|null
* @throws
*/
public function post($route, $handler)
{
return $this->addRoute($route, $handler, 'post');
}
/**
* @param $route
* @param $handler
* @return mixed|Node|null
* @throws
*/
public function get($route, $handler)
{
return $this->addRoute($route, $handler, 'get');
}
/**
* @param $route
* @param $handler
* @return mixed|Node|null
* @throws
*/
public function options($route, $handler)
{
return $this->addRoute($route, $handler, 'options');
}
/**
* @param $port
* @param Closure $closure
* @throws
*/
public function listen(int $port, Closure $closure)
{
2020-08-31 12:38:32 +08:00
$stdClass = Snowflake::createObject(Handler::class);
2020-08-31 01:27:08 +08:00
$this->group(['prefix' => $port], $closure, $stdClass);
}
/**
* @param $route
* @param $handler
* @return Any
*/
public function any($route, $handler)
{
$nodes = [];
foreach (['get', 'post', 'options', 'put', 'delete'] as $method) {
$nodes[] = $this->addRoute($route, $handler, $method);
}
return new Any($nodes);
}
/**
* @param $route
* @param $handler
* @return mixed|Node|null
* @throws
*/
public function delete($route, $handler)
{
return $this->addRoute($route, $handler, 'delete');
}
/**
* @param $route
* @param $handler
* @return mixed|Node|null
* @throws
*/
public function put($route, $handler)
{
return $this->addRoute($route, $handler, 'put');
}
/**
* @param $value
* @param $index
* @param $method
* @return Node
* @throws
*/
public function NodeInstance($value, $index = 0, $method = 'get')
{
$node = new Node();
$node->childes = [];
$node->path = $value;
$node->index = $index;
2020-09-04 18:47:22 +08:00
$node->method = $method;
2020-08-31 01:27:08 +08:00
$name = array_column($this->groupTacks, 'namespace');
$dir = array_column($this->groupTacks, 'dir');
if (!empty($dir)) {
array_unshift($name, implode('\\', $dir));
} else {
2020-09-02 14:07:16 +08:00
if ($method == 'package' || $method == 'receive') {
$dir = 'App\\Listener';
2020-08-31 01:27:08 +08:00
} else {
$dir = $this->dir;
}
array_unshift($name, $dir);
}
if (!empty($name) && $name = array_filter($name)) {
$node->namespace = $name;
}
$name = array_column($this->groupTacks, 'middleware');
if (!empty($name) && $name = array_filter($name)) {
$node->bindMiddleware($name);
}
$options = array_column($this->groupTacks, 'options');
if (!empty($options) && is_array($options)) {
$node->bindOptions($options);
}
$rules = array_column($this->groupTacks, 'filter');
$rules = array_shift($rules);
if (!empty($rules) && is_array($rules)) {
$node->filter($rules);
}
return $node;
}
/**
* @param array $config
* @param callable $callback
* 路由分组
* @param null $stdClass
*/
public function group(array $config, callable $callback, $stdClass = null)
{
$this->groupTacks[] = $config;
if ($stdClass) {
$callback($stdClass);
} else {
$callback($this);
}
array_pop($this->groupTacks);
}
/**
* @return string
*/
public function addPrefix()
{
$prefix = array_column($this->groupTacks, 'prefix');
$prefix = array_filter($prefix);
if (empty($prefix)) {
return '';
}
return '/' . implode('/', $prefix);
}
/**
* @param array $explode
2020-09-04 18:47:22 +08:00
* @param $method
2020-08-31 01:27:08 +08:00
* @return Node|null
* 查找指定路由
*/
2020-09-04 18:47:22 +08:00
public function tree_search($explode, $method)
2020-08-31 01:27:08 +08:00
{
if (empty($explode)) {
2020-09-04 18:47:22 +08:00
return $this->nodes[$method]['/'] ?? null;
2020-08-31 01:27:08 +08:00
}
$first = array_shift($explode);
2020-09-04 18:47:22 +08:00
if (!($parent = $this->nodes[$method][$first] ?? null)) {
2020-08-31 01:27:08 +08:00
return null;
}
if (empty($explode)) {
return $parent->findNode('/');
}
while ($value = array_shift($explode)) {
$node = $parent->findNode($value);
if (!$node) {
break;
}
$parent = $node;
}
return $parent;
}
/**
* @param $path
* @return array
* '*'
*/
public function split($path)
{
$prefix = $this->addPrefix();
$path = ltrim($path, '/');
if (!empty($prefix)) {
$path = $prefix . '/' . $path;
}
$explode = array_filter(explode('/', $path));
if (empty($explode)) {
return ['/', []];
}
$first = array_shift($explode);
if (empty($explode)) {
$explode = [];
}
return [$first, $explode];
}
/**
* @return array
*/
public function each()
{
$paths = [];
foreach ($this->nodes as $node) {
/** @var Node[] $node */
foreach ($node as $_node) {
if ($_node->path == '/') {
continue;
}
2020-09-04 18:47:22 +08:00
$path = strtoupper($_node->method) . ' : ' . $_node->path;
2020-08-31 01:27:08 +08:00
if (!empty($_node->childes)) {
$path = $this->readByChild($_node->childes, $path);
}
$paths[] = $path;
}
}
return $this->readByArray($paths);
}
/**
* @param $array
* @param array $returns
* @return array
*/
private function readByArray($array, $returns = [])
{
foreach ($array as $value) {
if (empty($value)) {
continue;
}
if (is_array($value)) {
$returns = $this->readByArray($value, $returns);
} else {
[$method, $route] = explode(' : ', $value);
$returns[] = ['method' => $method, 'route' => $route];
}
}
return $returns;
}
/**
* @param $child
* @param string $paths
* @return array
*/
private function readByChild($child, $paths = '')
{
$newPath = [];
/** @var Node $item */
foreach ($child as $item) {
if ($item->path == '/') {
continue;
}
if (!empty($item->childes)) {
$newPath[] = $this->readByChild($item->childes, $paths . '/' . $item->path);
} else {
[$first, $route] = explode(' : ', $paths);
2020-09-04 18:47:22 +08:00
$newPath[] = strtoupper($item->method) . ' : ' . $route . '/' . $item->path;
2020-08-31 01:27:08 +08:00
}
}
return $newPath;
}
/**
* @return mixed
* @throws
*/
public function dispatch()
{
$request = Context::getContext('request');
if (!($node = $this->find_path($request))) {
2020-09-04 18:47:22 +08:00
return JSON::to(404, 'Page not found or method not allowed.');
2020-08-31 01:27:08 +08:00
}
2020-09-04 18:47:22 +08:00
if (empty($node->callback)) {
return JSON::to(404, 'Page not found.');
2020-08-31 01:27:08 +08:00
}
return call_user_func($node->callback, $request);
}
2020-09-07 10:58:39 +08:00
2020-08-31 01:27:08 +08:00
/**
2020-09-07 10:51:23 +08:00
* @param Request $request
2020-08-31 01:27:08 +08:00
* @return Node|false|int|mixed|string|null
2020-09-07 10:58:39 +08:00
* 树干搜索
2020-08-31 01:27:08 +08:00
*/
private function find_path($request)
{
2020-09-07 10:42:10 +08:00
$method = $request->getMethod();
if (!isset($this->nodes[$method])) {
return null;
}
$methods = $this->nodes[$method];
2020-09-07 10:54:49 +08:00
$uri = ltrim($request->headers->getHeader('request_uri'), '/');
2020-09-07 17:39:51 +08:00
if (empty($uri)) {
$uri = '/';
}
2020-09-07 10:42:10 +08:00
if (!isset($methods[$uri])) {
2020-09-07 11:16:41 +08:00
if ($request->isOption) {
return $this->search_options($request);
}
2020-09-07 10:42:10 +08:00
return null;
}
return $this->nodes[$method][$uri];
2020-09-07 10:58:39 +08:00
}
2020-09-07 11:16:41 +08:00
/**
* @param $request
* @return Node|null
*/
private function search_options($request)
{
$method = $request->getMethod();
if (!isset($this->nodes[$method])) {
return null;
}
if (!isset($this->nodes[$method]['*'])) {
return null;
}
return $this->nodes[$method]['*'];
$node = $this->tree_search(['*'], $request->getMethod());
if (!($node instanceof Node)) {
return null;
}
return $node;
}
2020-09-07 10:58:39 +08:00
/**
* @param $request
* @return Node|null
* 树杈搜索
*/
private function Branch_search($request)
{
2020-09-04 18:47:22 +08:00
$node = $this->tree_search($request->getExplode(), $request->getMethod());
2020-08-31 01:27:08 +08:00
if ($node instanceof Node) {
return $node;
}
if (!$request->isOption) {
return null;
}
2020-09-04 18:47:22 +08:00
$node = $this->tree_search(['*'], $request->getMethod());
2020-08-31 01:27:08 +08:00
if (!($node instanceof Node)) {
return null;
}
return $node;
}
2020-09-07 10:58:39 +08:00
2020-08-31 01:27:08 +08:00
/**
* @throws
*/
2020-09-01 03:16:30 +08:00
public function loadRouterSetting()
2020-08-31 01:27:08 +08:00
{
2020-09-01 03:17:53 +08:00
$prefix = APP_PATH . 'app/Http/';
/** @var Annotation $annotation */
2020-09-03 11:39:20 +08:00
$annotation = Snowflake::app()->annotation;
2020-09-01 03:17:53 +08:00
$annotation->register('http', Annotation::class);
$annotation = $annotation->get('http');
$annotation->registration_notes($prefix . 'Interceptor', 'App\Http\Interceptor');
$annotation->registration_notes($prefix . 'Limits', 'App\Http\Limits');
2020-09-04 17:58:26 +08:00
$annotation->registration_notes($prefix . 'Middleware', 'App\Http\Middleware');
2020-09-01 03:17:53 +08:00
2020-09-01 03:16:30 +08:00
$this->loadRouteDir(APP_PATH . '/routes');
2020-08-31 01:27:08 +08:00
}
/**
* @param $path
* @throws Exception
* 加载目录下的路由文件
*/
2020-09-01 03:16:30 +08:00
private function loadRouteDir($path)
2020-08-31 01:27:08 +08:00
{
2020-09-01 03:16:30 +08:00
$files = glob($path . '/*');
for ($i = 0; $i < count($files); $i++) {
2020-09-01 03:38:27 +08:00
if (is_dir($files[$i])) {
$this->loadRouteDir($files[$i]);
} else {
$this->loadRouterFile($files[$i]);
2020-08-31 01:27:08 +08:00
}
}
}
2020-09-01 03:38:27 +08:00
/**
* @param $files
* @throws Exception
*/
private function loadRouterFile($files)
{
try {
$router = $this;
include_once "{$files}";
} catch (Exception $exception) {
$this->error($exception->getMessage());
} finally {
if (isset($exception)) {
unset($exception);
}
}
}
2020-08-31 01:27:08 +08:00
}