Skip to content

Commit

Permalink
Merge pull request #12 from topyao/master
Browse files Browse the repository at this point in the history
更新路由,移除domain
  • Loading branch information
bbuugg authored Jul 16, 2022
2 parents bef163b + 31e9931 commit a35eb89
Show file tree
Hide file tree
Showing 14 changed files with 97 additions and 145 deletions.
9 changes: 3 additions & 6 deletions src/framework/src/Console/Commands/RouteListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class RouteListCommand extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
$table = new Table(new ConsoleOutput());
$table->setHeaders(['Methods', 'URI', 'Action', 'Middlewares', 'Domain']);
$table->setHeaders(['Methods', 'URI', 'Action', 'Middlewares']);
foreach ($this->getRoutes() as $route) {
/** @var Route $route */
$action = $route->getAction();
Expand All @@ -49,7 +49,6 @@ public function execute(InputInterface $input, OutputInterface $output)
$route->getPath(),
$action,
implode(PHP_EOL, $route->getMiddlewares()),
$route->getDomain() ?: '*',
]);
}
$table->render();
Expand All @@ -74,10 +73,8 @@ protected function getRoutes(): Collection
$routes = [];
foreach ($routeCollector->all() as $registeredRoute) {
foreach ($registeredRoute as $route) {
foreach ($route as $item) {
if (! in_array($item, $routes)) {
$routes[] = $item;
}
if (!in_array($route, $routes)) {
$routes[] = $route;
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/http-server/src/Middlewares/RoutingMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public function __construct(protected RouteCollector $routeCollector)
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$route = $this->routeCollector->resolve($request);
$handler->prependMiddlewares($route->getMiddlewares());
$route = $this->routeCollector->resolveRequest($request);
$handler->appendMiddlewares($route->getMiddlewares());
return $handler->handle($request->withAttribute(Route::class, $route));
}
}
10 changes: 1 addition & 9 deletions src/http-server/src/RequestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,10 @@ public function handle(ServerRequestInterface $request): ResponseInterface
return $this->handleRequest($request);
}

/**
* 向尾部追加中间件.
*/
public function appendMiddlewares(array $middlewares): void
{
array_push($this->middlewares, ...$middlewares);
}

/**
* 向当前中间件后插入中间件.
*/
public function prependMiddlewares(array $middlewares): void
public function appendMiddlewares(array $middlewares): void
{
array_unshift($this->middlewares, ...$middlewares);
}
Expand Down
3 changes: 1 addition & 2 deletions src/http-server/src/RouteCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ public static function collectMethod(string $class, string $method, object $attr
{
if ($attribute instanceof MappingInterface && self::$class === $class && !is_null(self::$router)) {
self::$router->request($attribute->path, [$class, $method], $attribute->methods)
->middlewares($attribute->middlewares)
->domain($attribute->domain);
->middlewares($attribute->middlewares);
}
}

Expand Down
12 changes: 7 additions & 5 deletions src/routing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,30 @@

$router = new Router();

$router->get('index/{name}', function($name) { // 必选name
$router->get('index/{name}', function($name) {
return $name;
});

// 路由分组示例
$router->prefix('api')
->middleware('api')
->middlewares('api')
->pattterns(['id' => '\d+'])
->group(function(Router $router) {
$router->get('/user/{id}', function($id = 0) {
var_dump('user');
})->middlewares('auth');
$router->middleware('user')->group(function() {
$router->middlewares('user')->group(function() {
//
}
});
});

// 带参数类型限制, 其中id只有为数字的时候会匹配到
$router->get('/book/{id:\d+}', 'BookController::show');

// 解析路由,返回匹配到的Route对象
$route = $router->getRouteCollector()->resolve('GET', '/');
// 或者你可以传入一个ServerRequestInterface对象
$route = $router->getRouteCollector()->resolveRequest($request);

var_dump($route);
```
Expand All @@ -37,6 +39,6 @@ $router->namespace('App\Http\Controllers')->get('/', 'Index::index');
```

- prefix
- middleware
- middlewares
- namespace
- patterns
1 change: 0 additions & 1 deletion src/routing/src/Annotations/RequestMapping.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ public function __construct(
public string $path = '/',
array $methods = [],
public array $middlewares = [],
public string $domain = ''
) {
if (! empty($methods)) {
$this->methods = $methods;
Expand Down
25 changes: 0 additions & 25 deletions src/routing/src/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,6 @@ class Route
*/
protected array $middlewares = [];

/**
* 域名
*/
protected string $domain = '';
protected string $compiledDomain = '';

/**
* 初始化数据.
*/
Expand All @@ -69,25 +63,6 @@ public function __construct(protected array $methods, string $path, protected Cl
}
}

public function getCompiledDomain(): string
{
return $this->compiledDomain;
}

public function domain(string $domain): Route
{
if ($domain !== '') {
$this->domain = $domain;
$this->compiledDomain = '#^' . str_replace(['.', '*'], ['\.', '(.+?)'], $domain) . '$#iU';
}
return $this;
}

public function getDomain(): string
{
return $this->domain;
}

/**
* 获取路由参数规则.
*/
Expand Down
28 changes: 7 additions & 21 deletions src/routing/src/RouteCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Max\Routing\Exceptions\RouteNotFoundException;
use Psr\Http\Message\ServerRequestInterface;
use function array_key_exists;
use function is_null;
use function preg_match;

class RouteCollector
Expand All @@ -30,9 +29,8 @@ class RouteCollector
*/
public function add(Route $route): void
{
$domain = $route->getCompiledDomain();
foreach ($route->getMethods() as $method) {
$this->routes[$method][$domain][] = $route;
$this->routes[$method][] = $route;
}
}

Expand All @@ -48,29 +46,16 @@ public function all(): array
* @throws MethodNotAllowedException
* @throws RouteNotFoundException
*/
public function resolve(ServerRequestInterface $request): Route
public function resolveRequest(ServerRequestInterface $request): Route
{
$path = '/' . trim($request->getUri()->getPath(), '/');
$method = $request->getMethod();
$map = $this->routes[$method] ?? throw new MethodNotAllowedException('Method not allowed: ' . $method, 405);
if (!$resolvedRoute = $this->resolveRoute($map[''] ?? [], $path)) {
foreach ($map as $domain => $routes) {
if ($domain === '') {
continue;
}
if (preg_match($domain, $request->getUri()->getHost())) {
$resolvedRoute = $this->resolveRoute($routes, $path);
}
}
}
return $resolvedRoute ?? throw new RouteNotFoundException('Not Found', 404);
return $this->resolve($method, $path);
}

/**
* @param array<Route> $routes
*/
protected function resolveRoute(array $routes, string $path): ?Route
public function resolve(string $method, string $path)
{
$routes = $this->routes[$method] ?? throw new MethodNotAllowedException('Method not allowed: ' . $method, 405);
foreach ($routes as $route) {
if ($route->getPath() === $path) {
return clone $route;
Expand All @@ -87,6 +72,7 @@ protected function resolveRoute(array $routes, string $path): ?Route
return $resolvedRoute;
}
}
return null;

throw new RouteNotFoundException('Not Found', 404);
}
}
26 changes: 6 additions & 20 deletions src/routing/src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,12 @@ class Router
* @param array $patterns 参数规则
* @param array $middlewares 中间件
* @param string $namespace 命名空间
* @param string $domain 域名
*/
public function __construct(
protected string $prefix = '',
protected array $patterns = [],
protected string $namespace = '',
protected array $middlewares = [],
protected string $domain = '',
?RouteCollector $routeCollector = null
) {
$this->routeCollector = $routeCollector ?? new RouteCollector();
Expand Down Expand Up @@ -102,13 +100,13 @@ public function request(string $path, array|Closure|string $action, array $metho
if (is_string($action)) {
$action = explode('::', $this->formatController($action), 2);
}
if (is_array($action) && count($action) === 2) {
[$controller, $action] = $action;
$action = [$this->formatController($controller), $action];
}
if (is_array($action) || $action instanceof Closure) {
if ($action instanceof Closure || count($action) === 2) {
if (is_array($action)) {
[$controller, $action] = $action;
$action = [$this->formatController($controller), $action];
}
$route = new Route($methods, $this->prefix . $path, $action, $this->patterns);
$this->routeCollector->add($route->middlewares($this->middlewares)->domain($this->domain));
$this->routeCollector->add($route->middlewares($this->middlewares));

return $route;
}
Expand All @@ -134,18 +132,6 @@ public function middleware(string ...$middlewares): Router
return $new;
}

/**
* 指定域名
* Example: *.git.com / www.git.com.
*/
public function domain(string $domain): Router
{
$new = clone $this;
$new->domain = $domain;

return $new;
}

/**
* 变量规则.
*/
Expand Down
15 changes: 7 additions & 8 deletions src/view/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,17 @@ return [
],
];

## 使用
```

> 如果你使用MaxPHP, 则可以直接注入Renderer实例来使用,否则需要按照下面的方式使用
## 使用

```php
$engine = config('view.engine');
$renderer = new Renderer(new $engine(config('view.options')));
return $renderer->render('index', ['test' => ['123']]);
$viewFactory = new ViewFactory(config('view'));
$renderer = $viewFactory->getRenderer();
$renderer->assign('key', 'value');
$renderer->render('index', ['key2' => 'value2']);
```

## 自定义引擎

自定义引擎必须实现`ViewEngineInterface`接口, 将新的引擎实例传递给渲染器即可

> 官网:https://www.1kmb.com
自定义引擎必须实现`ViewEngineInterface`接口
25 changes: 10 additions & 15 deletions src/view/publish/view.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,15 @@
*/

return [
'default' => 'blade',
'engines' => [
'blade' => [
'engine' => 'Max\View\Engines\Blade',
'options' => [
// 模板目录
'path' => __DIR__ . '/../views/',
// 编译和缓存目录
'compileDir' => __DIR__ . '/../runtime/cache/views/',
// 模板缓存
'cache' => false,
// 模板后缀
'suffix' => '.blade.php',
],
],
'engine' => 'Max\View\Engines\Blade',
'options' => [
// 模板目录
'path' => __DIR__ . '/../views/',
// 编译和缓存目录
'compileDir' => __DIR__ . '/../runtime/cache/views/',
// 模板缓存
'cache' => false,
// 模板后缀
'suffix' => '.blade.php',
],
];
Loading

0 comments on commit a35eb89

Please sign in to comment.