RouteParser.php 7.3 KB

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