RouteParser.php 7.8 KB

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