You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuRoute.php 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. namespace Luticate\Utils\Controller;
  3. use FastRoute\Dispatcher;
  4. use Luticate\Utils\Business\LuBusiness;
  5. use Luticate\Utils\Business\LuBusinessException;
  6. use Luticate\Utils\Business\LuDocParser;
  7. use Luticate\Utils\Dbo\LuDboConstraintException;
  8. use Luticate\Utils\Dbo\LuDboDeserializeException;
  9. use FastRoute\DataGenerator\GroupCountBased as DataGeneratorGroupCountBased;
  10. use FastRoute\Dispatcher\GroupCountBased as DispatcherGroupCountBased;
  11. use FastRoute\RouteCollector;
  12. use FastRoute\RouteParser\Std;
  13. use Luticate\Utils\Dbo\LuRouteDbo;
  14. use Luticate\Utils\LuAbstractMiddleware;
  15. class LuRoute {
  16. const REG_UINT = "[0-9]+";
  17. const REG_INT = "\\-?" . self::REG_UINT;
  18. const REG_BOOL = "true|false";
  19. /**
  20. * @var DispatcherGroupCountBased
  21. */
  22. private $_dispatcher = null;
  23. /**
  24. * @var string[]
  25. */
  26. private $middleware = array('Luticate\Utils\ParametersMiddleware');
  27. /**
  28. * @var LuRouteDbo[]
  29. */
  30. private $routes = array();
  31. /**
  32. * @var LuRoute
  33. */
  34. private static $instance = null;
  35. private function __construct()
  36. {
  37. }
  38. public static function getInstance()
  39. {
  40. if (is_null(self::$instance)) {
  41. self::$instance = new static();
  42. }
  43. return self::$instance;
  44. }
  45. public function getRoutes()
  46. {
  47. return $this->routes;
  48. }
  49. /**
  50. * @param $middleware string
  51. */
  52. public function addMiddleware($middleware)
  53. {
  54. $this->middleware[] = $middleware;
  55. }
  56. public function setup()
  57. {
  58. $routeCollector = new RouteCollector(new Std(), new DataGeneratorGroupCountBased());
  59. foreach ($this->getRoutes() as $route) {
  60. $routeCollector->addRoute($route->getMethod(), $route->getUrl(), function() use($route)
  61. {
  62. $router = static::getInstance();
  63. return $router->execute($route);
  64. });
  65. }
  66. $this->_dispatcher = new DispatcherGroupCountBased($routeCollector->getData());
  67. }
  68. public function execute(LuRouteDbo $route)
  69. {
  70. $middlewares = [];
  71. foreach ($route->getMiddlewares() as $middlewareName) {
  72. /**
  73. * @var $middleware LuAbstractMiddleware
  74. */
  75. $middleware = new $middlewareName();
  76. $middleware->onBefore($route);
  77. $middlewares[] = $middleware;
  78. }
  79. $reflect = new \ReflectionMethod($route->getControllerClass(), $route->getControllerMethod());
  80. $params = $reflect->getParameters();
  81. $doc = new LuDocParser($reflect->getDocComment());
  82. $doc->parse();
  83. $args = array();
  84. foreach ($params as $param) {
  85. try {
  86. if ($param->isOptional()) {
  87. $value = null;
  88. if (LuBusiness::hasParam([$param->getName()])) {
  89. $value = $this->getParam($param, LuBusiness::getParam($param->getName()));
  90. }
  91. else {
  92. $value = $param->getDefaultValue();
  93. }
  94. $args[$param->getName()] = $value;
  95. }
  96. else {
  97. $args[$param->getName()] = $this->getParam($param, LuBusiness::checkParam($param->getName()));
  98. }
  99. if (array_key_exists($param->getName(), $doc->getParams())) {
  100. foreach ($doc->getParams()[$param->getName()]->getConstraints() as $constraint) {
  101. call_user_func_array([$args[$param->getName()], $constraint->getMethod()],
  102. $constraint->getArguments());
  103. }
  104. }
  105. }
  106. catch (LuDboConstraintException $e)
  107. {
  108. $paramName = $param->getName();
  109. LuBusiness::badInput("Invalid value for '${paramName}': " . $e->getMessage());
  110. }
  111. }
  112. $controller = $route->getControllerClass();
  113. $controllerInstance = new $controller();
  114. $result = call_user_func_array(array($controllerInstance, $route->getControllerMethod()), $args);
  115. foreach ($middlewares as $middleware) {
  116. $middleware->onAfter($route, $result);
  117. }
  118. return $result;
  119. }
  120. public function dispatch(string $httpMethod, string $url)
  121. {
  122. $routeInfo = $this->_dispatcher->dispatch($httpMethod, $url);
  123. if ($routeInfo[0] == Dispatcher::NOT_FOUND) {
  124. throw new LuBusinessException("Route not found", 404);
  125. }
  126. else if ($routeInfo[0] == Dispatcher::METHOD_NOT_ALLOWED) {
  127. throw new LuBusinessException("Method not allowed", 405);
  128. }
  129. else {
  130. $handler = $routeInfo[1];
  131. $vars = $routeInfo[2];
  132. $handler($vars);
  133. }
  134. }
  135. private function getClassName(\ReflectionParameter $param) {
  136. preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
  137. return isset($matches[1]) ? $matches[1] : null;
  138. }
  139. private function getParam(\ReflectionParameter $param, $value)
  140. {
  141. $typedValue = null;
  142. $className = $this->getClassName($param);
  143. if (is_null($className)) {
  144. $typedValue = $value;
  145. }
  146. else {
  147. $class = $param->getClass();
  148. try
  149. {
  150. $json = json_decode($value, true);
  151. if (is_null($json)) {
  152. $json = $value . "";
  153. }
  154. $typedValue = call_user_func_array(array($class->getName(), "jsonDeserialize"), array($json));
  155. }
  156. catch (LuDboDeserializeException $e)
  157. {
  158. throw $e;
  159. }
  160. catch (\Exception $e)
  161. {
  162. LuLog::log($e);
  163. LuBusiness::badInput("Unable to parse JSON value for '" . $param->getName() . "'");
  164. }
  165. }
  166. return $typedValue;
  167. }
  168. public function addRoute(string $httpMethod, string $url, string $controller, string $method, $permissions = array(), $middlewares = array())
  169. {
  170. if (!is_array($permissions)) {
  171. $permissions = array($permissions);
  172. }
  173. if (!is_array($middlewares)) {
  174. $middlewares = array($middlewares);
  175. }
  176. if (strpos($controller, "\\") === false) {
  177. $controller = "App\\Controller\\" . $controller . "Controller";
  178. }
  179. $route = new LuRouteDbo();
  180. $route->setUrl($url);
  181. $route->setControllerClass($controller);
  182. $route->setControllerMethod($method);
  183. $route->setMiddlewares($middlewares);
  184. $route->setPermissions($permissions);
  185. $route->setMethod($httpMethod);
  186. $this->routes[] = $route;
  187. }
  188. public function get(string $url, string $controller, string $method, $permissions = array(), $middleware = array())
  189. {
  190. $this->addRoute("GET", $url, $controller, $method, $permissions, $middleware);
  191. }
  192. public function post(string $url, string $controller, string $method, $permissions = array(), $middleware = array())
  193. {
  194. $this->addRoute("POST", $url, $controller, $method, $permissions, $middleware);
  195. }
  196. public function put(string $url, string $controller, string $method, $permissions = array(), $middleware = array())
  197. {
  198. $this->addRoute("PUT", $url, $controller, $method, $permissions, $middleware);
  199. }
  200. public function delete(string $url, string $controller, string $method, $permissions = array(), $middleware = array())
  201. {
  202. $this->addRoute("DELETE", $url, $controller, $method, $permissions, $middleware);
  203. }
  204. }