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

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