RouteConfig.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Robin McCorkell <robin@mccorkell.me.uk>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\AppFramework\Routing;
  30. use OC\AppFramework\DependencyInjection\DIContainer;
  31. use OC\Route\Router;
  32. /**
  33. * Class RouteConfig
  34. * @package OC\AppFramework\routing
  35. */
  36. class RouteConfig {
  37. /** @var DIContainer */
  38. private $container;
  39. /** @var Router */
  40. private $router;
  41. /** @var array */
  42. private $routes;
  43. /** @var string */
  44. private $appName;
  45. /** @var string[] */
  46. private $controllerNameCache = [];
  47. protected $rootUrlApps = [
  48. 'cloud_federation_api',
  49. 'core',
  50. 'files_sharing',
  51. 'files',
  52. 'settings',
  53. 'spreed',
  54. ];
  55. /**
  56. * @param \OC\AppFramework\DependencyInjection\DIContainer $container
  57. * @param \OC\Route\Router $router
  58. * @param array $routes
  59. * @internal param $appName
  60. */
  61. public function __construct(DIContainer $container, Router $router, $routes) {
  62. $this->routes = $routes;
  63. $this->container = $container;
  64. $this->router = $router;
  65. $this->appName = $container['AppName'];
  66. }
  67. /**
  68. * The routes and resource will be registered to the \OCP\Route\IRouter
  69. */
  70. public function register() {
  71. // parse simple
  72. $this->processIndexRoutes($this->routes);
  73. // parse resources
  74. $this->processIndexResources($this->routes);
  75. /*
  76. * OCS routes go into a different collection
  77. */
  78. $oldCollection = $this->router->getCurrentCollection();
  79. $this->router->useCollection($oldCollection . '.ocs');
  80. // parse ocs simple routes
  81. $this->processOCS($this->routes);
  82. // parse ocs simple routes
  83. $this->processOCSResources($this->routes);
  84. $this->router->useCollection($oldCollection);
  85. }
  86. private function processOCS(array $routes): void {
  87. $ocsRoutes = $routes['ocs'] ?? [];
  88. foreach ($ocsRoutes as $ocsRoute) {
  89. $this->processRoute($ocsRoute, 'ocs.');
  90. }
  91. }
  92. /**
  93. * Creates one route base on the give configuration
  94. * @param array $routes
  95. * @throws \UnexpectedValueException
  96. */
  97. private function processIndexRoutes(array $routes): void {
  98. $simpleRoutes = $routes['routes'] ?? [];
  99. foreach ($simpleRoutes as $simpleRoute) {
  100. $this->processRoute($simpleRoute);
  101. }
  102. }
  103. protected function processRoute(array $route, string $routeNamePrefix = ''): void {
  104. $name = $route['name'];
  105. $postfix = $route['postfix'] ?? '';
  106. $root = $this->buildRootPrefix($route, $routeNamePrefix);
  107. $url = $root . '/' . ltrim($route['url'], '/');
  108. $verb = strtoupper($route['verb'] ?? 'GET');
  109. $split = explode('#', $name, 2);
  110. if (count($split) !== 2) {
  111. throw new \UnexpectedValueException('Invalid route name: use the format foo#bar to reference FooController::bar');
  112. }
  113. [$controller, $action] = $split;
  114. $controllerName = $this->buildControllerName($controller);
  115. $actionName = $this->buildActionName($action);
  116. /*
  117. * The route name has to be lowercase, for symfony to match it correctly.
  118. * This is required because smyfony allows mixed casing for controller names in the routes.
  119. * To avoid breaking all the existing route names, registering and matching will only use the lowercase names.
  120. * This is also safe on the PHP side because class and method names collide regardless of the casing.
  121. */
  122. $routeName = strtolower($routeNamePrefix . $this->appName . '.' . $controller . '.' . $action . $postfix);
  123. $router = $this->router->create($routeName, $url)
  124. ->method($verb);
  125. // optionally register requirements for route. This is used to
  126. // tell the route parser how url parameters should be matched
  127. if (array_key_exists('requirements', $route)) {
  128. $router->requirements($route['requirements']);
  129. }
  130. // optionally register defaults for route. This is used to
  131. // tell the route parser how url parameters should be default valued
  132. $defaults = [];
  133. if (array_key_exists('defaults', $route)) {
  134. $defaults = $route['defaults'];
  135. }
  136. $defaults['caller'] = [$this->appName, $controllerName, $actionName];
  137. $router->defaults($defaults);
  138. }
  139. /**
  140. * For a given name and url restful OCS routes are created:
  141. * - index
  142. * - show
  143. * - create
  144. * - update
  145. * - destroy
  146. *
  147. * @param array $routes
  148. */
  149. private function processOCSResources(array $routes): void {
  150. $this->processResources($routes['ocs-resources'] ?? [], 'ocs.');
  151. }
  152. /**
  153. * For a given name and url restful routes are created:
  154. * - index
  155. * - show
  156. * - create
  157. * - update
  158. * - destroy
  159. *
  160. * @param array $routes
  161. */
  162. private function processIndexResources(array $routes): void {
  163. $this->processResources($routes['resources'] ?? []);
  164. }
  165. /**
  166. * For a given name and url restful routes are created:
  167. * - index
  168. * - show
  169. * - create
  170. * - update
  171. * - destroy
  172. *
  173. * @param array $resources
  174. * @param string $routeNamePrefix
  175. */
  176. protected function processResources(array $resources, string $routeNamePrefix = ''): void {
  177. // declaration of all restful actions
  178. $actions = [
  179. ['name' => 'index', 'verb' => 'GET', 'on-collection' => true],
  180. ['name' => 'show', 'verb' => 'GET'],
  181. ['name' => 'create', 'verb' => 'POST', 'on-collection' => true],
  182. ['name' => 'update', 'verb' => 'PUT'],
  183. ['name' => 'destroy', 'verb' => 'DELETE'],
  184. ];
  185. foreach ($resources as $resource => $config) {
  186. $root = $this->buildRootPrefix($config, $routeNamePrefix);
  187. // the url parameter used as id to the resource
  188. foreach ($actions as $action) {
  189. $url = $root . '/' . ltrim($config['url'], '/');
  190. $method = $action['name'];
  191. $verb = strtoupper($action['verb'] ?? 'GET');
  192. $collectionAction = $action['on-collection'] ?? false;
  193. if (!$collectionAction) {
  194. $url .= '/{id}';
  195. }
  196. if (isset($action['url-postfix'])) {
  197. $url .= '/' . $action['url-postfix'];
  198. }
  199. $controller = $resource;
  200. $controllerName = $this->buildControllerName($controller);
  201. $actionName = $this->buildActionName($method);
  202. $routeName = $routeNamePrefix . $this->appName . '.' . strtolower($resource) . '.' . $method;
  203. $route = $this->router->create($routeName, $url)
  204. ->method($verb);
  205. $route->defaults(['caller' => [$this->appName, $controllerName, $actionName]]);
  206. }
  207. }
  208. }
  209. private function buildRootPrefix(array $route, string $routeNamePrefix): string {
  210. $defaultRoot = $this->appName === 'core' ? '' : '/apps/' . $this->appName;
  211. $root = $route['root'] ?? $defaultRoot;
  212. if ($routeNamePrefix !== '') {
  213. // In OCS all apps are whitelisted
  214. return $root;
  215. }
  216. if (!\in_array($this->appName, $this->rootUrlApps, true)) {
  217. // Only allow root URLS for some apps
  218. return $defaultRoot;
  219. }
  220. return $root;
  221. }
  222. /**
  223. * Based on a given route name the controller name is generated
  224. * @param string $controller
  225. * @return string
  226. */
  227. private function buildControllerName(string $controller): string {
  228. if (!isset($this->controllerNameCache[$controller])) {
  229. $this->controllerNameCache[$controller] = $this->underScoreToCamelCase(ucfirst($controller)) . 'Controller';
  230. }
  231. return $this->controllerNameCache[$controller];
  232. }
  233. /**
  234. * Based on the action part of the route name the controller method name is generated
  235. * @param string $action
  236. * @return string
  237. */
  238. private function buildActionName(string $action): string {
  239. return $this->underScoreToCamelCase($action);
  240. }
  241. /**
  242. * Underscored strings are converted to camel case strings
  243. * @param string $str
  244. * @return string
  245. */
  246. private function underScoreToCamelCase(string $str): string {
  247. $pattern = '/_[a-z]?/';
  248. return preg_replace_callback(
  249. $pattern,
  250. function ($matches) {
  251. return strtoupper(ltrim($matches[0], '_'));
  252. },
  253. $str);
  254. }
  255. }