20240120-ljl-routeConfig
ljl 10 months ago
parent f321da2c4e
commit 5fedd15b12

@ -40,6 +40,8 @@ class ErrorCodeConst {
const systemPermissionDenied = 'system.permission-denied'; const systemPermissionDenied = 'system.permission-denied';
const systemDaoDefineUncorrect = 'system.dao-define-uncorrect'; const systemDaoDefineUncorrect = 'system.dao-define-uncorrect';
const systemDaoNotFound = 'system.dao-not-found'; const systemDaoNotFound = 'system.dao-not-found';
const systemRouteNotFound = 'system.route-not-found';
const systemMethodNotAllow = 'system.method-not-allow';
const systemAttributeDefinedUncorrect = 'system.attribute-defined-uncorrect'; const systemAttributeDefinedUncorrect = 'system.attribute-defined-uncorrect';
const bizCommonError = 'biz.common-error'; const bizCommonError = 'biz.common-error';
const bizInvalidParameter = 'biz.invalid-parameter'; const bizInvalidParameter = 'biz.invalid-parameter';

@ -262,5 +262,6 @@ class OrderPrintController extends AbstractApiController {
} }
public function test() { public function test() {
var_dump('hahaha');
} }
} }

@ -0,0 +1,8 @@
<?php
namespace Exception;
class MethodNotAllowException extends BaseRuntimeException {
protected $httpCode = 405;
protected $errorCode = \ErrorCodeConst::systemMethodNotAllow;
}

@ -0,0 +1,8 @@
<?php
namespace Exception;
class RouteNotFoundException extends BaseRuntimeException {
protected $httpCode = 404;
protected $errorCode = \ErrorCodeConst::systemRouteNotFound;
}

@ -0,0 +1,12 @@
<?php
namespace Middleware;
class AbstractMiddleware {
public function handle(\Closure $next) {
$response = $next();
return $response;
}
}

@ -0,0 +1,82 @@
<?php
class Route {
private static $groupUri = '';
private static $routeMap = [];
public static function addRoute($methods, $uri, $action, $options = []) {
self::addRouteMap($uri, $action, $methods, $options);
}
public static function get($uri, $action, $options = []) {
self::addRouteMap($uri, $action, ['GET'], $options);
}
public static function post($uri, $action, $options = []) {
self::addRouteMap($uri, $action, ['POST'], $options);
}
public static function put($uri, $action, $options = []) {
self::addRouteMap($uri, $action, ['PUT'], $options);
}
public static function patch($uri, $action, $options = []) {
self::addRouteMap($uri, $action, ['PATCH'], $options);
}
public static function delete($uri, $action, $options = []) {
self::addRouteMap($uri, $action, ['DELETE'], $options);
}
public static function options($uri, $action, $options = []) {
self::addRouteMap($uri, $action, ['OPTIONS'], $options);
}
private static function addRouteMap($uri, $action, $methods, $options = []) {
if (empty($options['apps']) || in_array(Zc::C('appName'), $options['apps'])) {
return;
}
$actionRoute = self::getRouteByAction($action, $methods);
$route = self::$groupUri . $uri;
self::$routeMap[$route] = [
'actionRoute' => $actionRoute,
'methods' => $methods,
'middlewares' => $options['middlewares'] ?: []
];
}
public static function group($groupUri, $callback, $moudle = '', $options = []) {
self::$groupUri = $groupUri;
$callback();
self::$groupUri = '';
}
public static function getRouteMap() {
return self::$routeMap;
}
private static function getRouteByAction($action, $moudle = '') {
$action = trim($action, '/');
$actionItems = explode('/', $action);
$moudle = trim($moudle, '/');
$route = $moudle ? '/' . $moudle . '/' : '/';
foreach ($actionItems as $item) {
if (strpos($item, '@') !== false) {
list($controller, $method) = explode('@', $item);
$controller = str_replace('Controller', '', $controller);
$route .= self::toUnderScore($controller. '/' . $method);
} else {
$route .= $item . '/';
}
}
return $route;
}
private static function toUnderScore($str) {
$dstr = preg_replace_callback('/([A-Z])/', function ($matchs) {
return '_' . strtolower($matchs[0]);
}, $str);
return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
}
}

@ -0,0 +1,103 @@
<?php
use Exception\MethodNotAllowException;
use Exception\RouteNotFoundException;
class RouteManager {
private $routeConfigPath;
public function __construct($routeConfigPath = '') {
if ($routeConfigPath) {
$this->routeConfigPath = $routeConfigPath;
} else {
$this->routeConfigPath = APP_PATH . '/routes';
}
$this->initRoutes();
}
public function rewrite($route) {
$routeMap = Route::getRouteMap();
$routeInfo = $routeMap[$route];
$route = $routeInfo ? $routeInfo['actionRoute'] : $route;
$this->checkMethodAllow($routeInfo['methods']);
$this->checkActionExists($route);
return $route;
}
private function checkMethodAllow($allowMethods) {
$allowMethods = ['get', 'post'];
array_walk($allowMethods, function(&$value) {
$value = strtoupper($value);
});
if(!in_array(strtoupper($_SERVER['REQUEST_METHOD']), $allowMethods)) {
throw new MethodNotAllowException('Method not allow.');
}
}
private function checkActionExists($route) {
$routeItems = explode('/', trim($route, '/'));
$routeItemLen = count($routeItems);
if ($routeItemLen < 2) {
throw new RouteNotFoundException('Route[' . $route . '] can not parse.');
}
$action = $routeItems[$routeItemLen - 1];
$controller = $routeItems[$routeItemLen - 2];
$pathItems = array_slice($routeItems, 0, $routeItemLen - 2);
$controllerPath = '';
if (!empty($pathItems)) {
$controllerPath = implode('/', $pathItems);
}
$controllerDir = Zc::C(ZcConfigConst::DirFsLibsController);
$controllerClass = ucfirst($this->toCamel($controller)) . 'Controller';
$controllerFile = $controllerPath . '/' . 'class.' . $controllerClass . '.php';
if (!is_file($controllerDir . $controllerFile)) {
throw new RouteNotFoundException('Can nott find controller[' . $controllerFile . '].');
}
require_once($controllerDir . $controllerFile);
$reflection = new ReflectionClass($controllerClass);
if (!$reflection->hasMethod($this->toCamel($action))) {
throw new RouteNotFoundException('Can nott find method[' . $action . '] in ' . $controllerFile . '.');
}
}
private function initRoutes() {
$files = $this->getDirFiles($this->routeConfigPath);
foreach ($files as $file) {
require $file;
}
}
private function getDirFiles($path) {
$files = [];
if(is_dir($path)) {
$dir = scandir($path);
foreach($dir as $value) {
$file = $path . '/'. $value;
if ($value == '.' || $value == '..') {
continue;
} elseif (is_dir($file)) {
$files = array_merge($files, getDir($file));
} else {
$files[] = $file;
}
}
}
return $files;
}
private function toCamel($str) {
$array = explode('_', $str);
$result = $array[0];
$len = count($array);
if ($len > 1) {
for ($i = 1; $i < $len; $i++) {
$result .= ucfirst($array[$i]);
}
}
return $result;
}
}

@ -1,4 +1,7 @@
<?php <?php
use Exception\RouteNotFoundException;
class AppUrlHandler implements ZcUrlHandler { class AppUrlHandler implements ZcUrlHandler {
public function buildUrl($route, $params = '', $scheme = false, $host = false) { public function buildUrl($route, $params = '', $scheme = false, $host = false) {
@ -53,37 +56,9 @@ class AppUrlHandler implements ZcUrlHandler {
} }
} }
private function rewriteRoute($route){ private function rewriteRoute($route) {
$route = trim($route, '/'); $manager = new RouteManager();
return $manager->rewrite($route);
if (AppConst::isUseAppModuleApp() && (stripos($route, 'control/decrypt/') === 0)) {
return 'pdd/' . $route;
}
if ((AppConst::isPddRubyApp() || AppConst::isPddTaoBaiKeApp()) && $this->isUseRealRoute($route)) {
return $route;
}
if (AppConst::isRubyWeb()) {
if (stripos($route, 'ruby/') === 0) {
return $route;
} else {
return 'ruby/' . $route;
}
} else if (AppConst::isRubyDesktop()) {
if (stripos($route, 'ruby_dt/') === 0) {
return $route;
} else {
return 'ruby_dt/' . $route;
}
} else if (AppConst::isPddTaoBaiKeApp()) {
if (stripos($route, 'taobaike/') === 0) {
return $route;
} else {
return 'taobaike/' . $route;
}
}
return $route;
} }
private function isUseRealRoute($route){ private function isUseRealRoute($route){

@ -0,0 +1,7 @@
<?php
Route::group('/order', function() {
Route::get('/order_print/multi_shop', 'OrderPrintController@test', ['middleware' => [], 'apps' => []]);
Route::get('/order-print-test', 'OrderPrintController@test');
Route::get('/dgfdgs/sdfs', 'OrderPrintController@test');
}, 'order', ['middleware' => []]);

@ -4,6 +4,8 @@ require 'vendor/autoload.php';
$rootDir = dirname(__FILE__); $rootDir = dirname(__FILE__);
$appDir = 'app'; $appDir = 'app';
define('APP_PATH', $rootDir . '/app');
if (substr($_SERVER['HTTP_HOST'], -3, 3) === '.me') { if (substr($_SERVER['HTTP_HOST'], -3, 3) === '.me') {
@ini_set('display_errors', '1'); @ini_set('display_errors', '1');
error_reporting(E_ALL); error_reporting(E_ALL);

Loading…
Cancel
Save