RouteConfig.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\AppFramework\Routing;
  9. use OC\AppFramework\DependencyInjection\DIContainer;
  10. use OC\Route\Router;
  11. /**
  12. * Class RouteConfig
  13. * @package OC\AppFramework\routing
  14. */
  15. class RouteConfig {
  16. /** @var DIContainer */
  17. private $container;
  18. /** @var Router */
  19. private $router;
  20. /** @var array */
  21. private $routes;
  22. /** @var string */
  23. private $appName;
  24. /** @var string[] */
  25. private $controllerNameCache = [];
  26. protected $rootUrlApps = [
  27. 'cloud_federation_api',
  28. 'core',
  29. 'files_sharing',
  30. 'files',
  31. 'settings',
  32. 'spreed',
  33. ];
  34. /**
  35. * @param \OC\AppFramework\DependencyInjection\DIContainer $container
  36. * @param \OC\Route\Router $router
  37. * @param array $routes
  38. * @internal param $appName
  39. */
  40. public function __construct(DIContainer $container, Router $router, $routes) {
  41. $this->routes = $routes;
  42. $this->container = $container;
  43. $this->router = $router;
  44. $this->appName = $container['AppName'];
  45. }
  46. /**
  47. * The routes and resource will be registered to the \OCP\Route\IRouter
  48. */
  49. public function register() {
  50. // parse simple
  51. $this->processIndexRoutes($this->routes);
  52. // parse resources
  53. $this->processIndexResources($this->routes);
  54. /*
  55. * OCS routes go into a different collection
  56. */
  57. $oldCollection = $this->router->getCurrentCollection();
  58. $this->router->useCollection($oldCollection . '.ocs');
  59. // parse ocs simple routes
  60. $this->processOCS($this->routes);
  61. // parse ocs simple routes
  62. $this->processOCSResources($this->routes);
  63. $this->router->useCollection($oldCollection);
  64. }
  65. private function processOCS(array $routes): void {
  66. $ocsRoutes = $routes['ocs'] ?? [];
  67. foreach ($ocsRoutes as $ocsRoute) {
  68. $this->processRoute($ocsRoute, 'ocs.');
  69. }
  70. }
  71. /**
  72. * Creates one route base on the give configuration
  73. * @param array $routes
  74. * @throws \UnexpectedValueException
  75. */
  76. private function processIndexRoutes(array $routes): void {
  77. $simpleRoutes = $routes['routes'] ?? [];
  78. foreach ($simpleRoutes as $simpleRoute) {
  79. $this->processRoute($simpleRoute);
  80. }
  81. }
  82. protected function processRoute(array $route, string $routeNamePrefix = ''): void {
  83. $name = $route['name'];
  84. $postfix = $route['postfix'] ?? '';
  85. $root = $this->buildRootPrefix($route, $routeNamePrefix);
  86. $url = $root . '/' . ltrim($route['url'], '/');
  87. $verb = strtoupper($route['verb'] ?? 'GET');
  88. $split = explode('#', $name, 2);
  89. if (count($split) !== 2) {
  90. throw new \UnexpectedValueException('Invalid route name: use the format foo#bar to reference FooController::bar');
  91. }
  92. [$controller, $action] = $split;
  93. $controllerName = $this->buildControllerName($controller);
  94. $actionName = $this->buildActionName($action);
  95. /*
  96. * The route name has to be lowercase, for symfony to match it correctly.
  97. * This is required because smyfony allows mixed casing for controller names in the routes.
  98. * To avoid breaking all the existing route names, registering and matching will only use the lowercase names.
  99. * This is also safe on the PHP side because class and method names collide regardless of the casing.
  100. */
  101. $routeName = strtolower($routeNamePrefix . $this->appName . '.' . $controller . '.' . $action . $postfix);
  102. $router = $this->router->create($routeName, $url)
  103. ->method($verb);
  104. // optionally register requirements for route. This is used to
  105. // tell the route parser how url parameters should be matched
  106. if (array_key_exists('requirements', $route)) {
  107. $router->requirements($route['requirements']);
  108. }
  109. // optionally register defaults for route. This is used to
  110. // tell the route parser how url parameters should be default valued
  111. $defaults = [];
  112. if (array_key_exists('defaults', $route)) {
  113. $defaults = $route['defaults'];
  114. }
  115. $defaults['caller'] = [$this->appName, $controllerName, $actionName];
  116. $router->defaults($defaults);
  117. }
  118. /**
  119. * For a given name and url restful OCS routes are created:
  120. * - index
  121. * - show
  122. * - create
  123. * - update
  124. * - destroy
  125. *
  126. * @param array $routes
  127. */
  128. private function processOCSResources(array $routes): void {
  129. $this->processResources($routes['ocs-resources'] ?? [], 'ocs.');
  130. }
  131. /**
  132. * For a given name and url restful routes are created:
  133. * - index
  134. * - show
  135. * - create
  136. * - update
  137. * - destroy
  138. *
  139. * @param array $routes
  140. */
  141. private function processIndexResources(array $routes): void {
  142. $this->processResources($routes['resources'] ?? []);
  143. }
  144. /**
  145. * For a given name and url restful routes are created:
  146. * - index
  147. * - show
  148. * - create
  149. * - update
  150. * - destroy
  151. *
  152. * @param array $resources
  153. * @param string $routeNamePrefix
  154. */
  155. protected function processResources(array $resources, string $routeNamePrefix = ''): void {
  156. // declaration of all restful actions
  157. $actions = [
  158. ['name' => 'index', 'verb' => 'GET', 'on-collection' => true],
  159. ['name' => 'show', 'verb' => 'GET'],
  160. ['name' => 'create', 'verb' => 'POST', 'on-collection' => true],
  161. ['name' => 'update', 'verb' => 'PUT'],
  162. ['name' => 'destroy', 'verb' => 'DELETE'],
  163. ];
  164. foreach ($resources as $resource => $config) {
  165. $root = $this->buildRootPrefix($config, $routeNamePrefix);
  166. // the url parameter used as id to the resource
  167. foreach ($actions as $action) {
  168. $url = $root . '/' . ltrim($config['url'], '/');
  169. $method = $action['name'];
  170. $verb = strtoupper($action['verb'] ?? 'GET');
  171. $collectionAction = $action['on-collection'] ?? false;
  172. if (!$collectionAction) {
  173. $url .= '/{id}';
  174. }
  175. if (isset($action['url-postfix'])) {
  176. $url .= '/' . $action['url-postfix'];
  177. }
  178. $controller = $resource;
  179. $controllerName = $this->buildControllerName($controller);
  180. $actionName = $this->buildActionName($method);
  181. $routeName = $routeNamePrefix . $this->appName . '.' . strtolower($resource) . '.' . $method;
  182. $route = $this->router->create($routeName, $url)
  183. ->method($verb);
  184. $route->defaults(['caller' => [$this->appName, $controllerName, $actionName]]);
  185. }
  186. }
  187. }
  188. private function buildRootPrefix(array $route, string $routeNamePrefix): string {
  189. $defaultRoot = $this->appName === 'core' ? '' : '/apps/' . $this->appName;
  190. $root = $route['root'] ?? $defaultRoot;
  191. if ($routeNamePrefix !== '') {
  192. // In OCS all apps are whitelisted
  193. return $root;
  194. }
  195. if (!\in_array($this->appName, $this->rootUrlApps, true)) {
  196. // Only allow root URLS for some apps
  197. return $defaultRoot;
  198. }
  199. return $root;
  200. }
  201. /**
  202. * Based on a given route name the controller name is generated
  203. * @param string $controller
  204. * @return string
  205. */
  206. private function buildControllerName(string $controller): string {
  207. if (!isset($this->controllerNameCache[$controller])) {
  208. $this->controllerNameCache[$controller] = $this->underScoreToCamelCase(ucfirst($controller)) . 'Controller';
  209. }
  210. return $this->controllerNameCache[$controller];
  211. }
  212. /**
  213. * Based on the action part of the route name the controller method name is generated
  214. * @param string $action
  215. * @return string
  216. */
  217. private function buildActionName(string $action): string {
  218. return $this->underScoreToCamelCase($action);
  219. }
  220. /**
  221. * Underscored strings are converted to camel case strings
  222. * @param string $str
  223. * @return string
  224. */
  225. private function underScoreToCamelCase(string $str): string {
  226. $pattern = '/_[a-z]?/';
  227. return preg_replace_callback(
  228. $pattern,
  229. function ($matches) {
  230. return strtoupper(ltrim($matches[0], '_'));
  231. },
  232. $str);
  233. }
  234. }