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.0KB

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