RouteParser.php 7.2 KB

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