RouteConfig.php 7.5 KB

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