RouteBuilder.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Routing;
  16. use BadMethodCallException;
  17. use Cake\Core\App;
  18. use Cake\Core\Exception\MissingPluginException;
  19. use Cake\Core\Plugin;
  20. use Cake\Routing\Route\Route;
  21. use Cake\Utility\Inflector;
  22. use InvalidArgumentException;
  23. use RuntimeException;
  24. /**
  25. * Provides features for building routes inside scopes.
  26. *
  27. * Gives an easy to use way to build routes and append them
  28. * into a route collection.
  29. */
  30. class RouteBuilder
  31. {
  32. /**
  33. * Regular expression for auto increment IDs
  34. *
  35. * @var string
  36. */
  37. const ID = '[0-9]+';
  38. /**
  39. * Regular expression for UUIDs
  40. *
  41. * @var string
  42. */
  43. const UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}';
  44. /**
  45. * Default HTTP request method => controller action map.
  46. *
  47. * @var array
  48. */
  49. protected static $_resourceMap = [
  50. 'index' => ['action' => 'index', 'method' => 'GET', 'path' => ''],
  51. 'create' => ['action' => 'add', 'method' => 'POST', 'path' => ''],
  52. 'view' => ['action' => 'view', 'method' => 'GET', 'path' => ':id'],
  53. 'update' => ['action' => 'edit', 'method' => ['PUT', 'PATCH'], 'path' => ':id'],
  54. 'delete' => ['action' => 'delete', 'method' => 'DELETE', 'path' => ':id'],
  55. ];
  56. /**
  57. * Default route class to use if none is provided in connect() options.
  58. *
  59. * @var string
  60. */
  61. protected $_routeClass = 'Cake\Routing\Route\Route';
  62. /**
  63. * The extensions that should be set into the routes connected.
  64. *
  65. * @var string[]
  66. */
  67. protected $_extensions = [];
  68. /**
  69. * The path prefix scope that this collection uses.
  70. *
  71. * @var string
  72. */
  73. protected $_path;
  74. /**
  75. * The scope parameters if there are any.
  76. *
  77. * @var array
  78. */
  79. protected $_params;
  80. /**
  81. * Name prefix for connected routes.
  82. *
  83. * @var string
  84. */
  85. protected $_namePrefix = '';
  86. /**
  87. * The route collection routes should be added to.
  88. *
  89. * @var \Cake\Routing\RouteCollection
  90. */
  91. protected $_collection;
  92. /**
  93. * The list of middleware that routes in this builder get
  94. * added during construction.
  95. *
  96. * @var string[]
  97. */
  98. protected $middleware = [];
  99. /**
  100. * Constructor
  101. *
  102. * ### Options
  103. *
  104. * - `routeClass` - The default route class to use when adding routes.
  105. * - `extensions` - The extensions to connect when adding routes.
  106. * - `namePrefix` - The prefix to prepend to all route names.
  107. * - `middleware` - The names of the middleware routes should have applied.
  108. *
  109. * @param \Cake\Routing\RouteCollection $collection The route collection to append routes into.
  110. * @param string $path The path prefix the scope is for.
  111. * @param array $params The scope's routing parameters.
  112. * @param array $options Options list.
  113. */
  114. public function __construct(RouteCollection $collection, $path, array $params = [], array $options = [])
  115. {
  116. $this->_collection = $collection;
  117. $this->_path = $path;
  118. $this->_params = $params;
  119. if (isset($options['routeClass'])) {
  120. $this->_routeClass = $options['routeClass'];
  121. }
  122. if (isset($options['extensions'])) {
  123. $this->_extensions = $options['extensions'];
  124. }
  125. if (isset($options['namePrefix'])) {
  126. $this->_namePrefix = $options['namePrefix'];
  127. }
  128. if (isset($options['middleware'])) {
  129. $this->middleware = (array)$options['middleware'];
  130. }
  131. }
  132. /**
  133. * Get or set default route class.
  134. *
  135. * @deprecated 3.5.0 Use getRouteClass/setRouteClass instead.
  136. * @param string|null $routeClass Class name.
  137. * @return string|null
  138. */
  139. public function routeClass($routeClass = null)
  140. {
  141. deprecationWarning(
  142. 'RouteBuilder::routeClass() is deprecated. ' .
  143. 'Use RouteBuilder::setRouteClass()/getRouteClass() instead.'
  144. );
  145. if ($routeClass === null) {
  146. return $this->getRouteClass();
  147. }
  148. $this->setRouteClass($routeClass);
  149. }
  150. /**
  151. * Set default route class.
  152. *
  153. * @param string $routeClass Class name.
  154. * @return $this
  155. */
  156. public function setRouteClass($routeClass)
  157. {
  158. $this->_routeClass = $routeClass;
  159. return $this;
  160. }
  161. /**
  162. * Get default route class.
  163. *
  164. * @return string
  165. */
  166. public function getRouteClass()
  167. {
  168. return $this->_routeClass;
  169. }
  170. /**
  171. * Get or set the extensions in this route builder's scope.
  172. *
  173. * Future routes connected in through this builder will have the connected
  174. * extensions applied. However, setting extensions does not modify existing routes.
  175. *
  176. * @deprecated 3.5.0 Use getExtensions/setExtensions instead.
  177. * @param string[]|string|null $extensions Either the extensions to use or null.
  178. * @return string[]|null
  179. */
  180. public function extensions($extensions = null)
  181. {
  182. deprecationWarning(
  183. 'RouteBuilder::extensions() is deprecated. ' .
  184. 'Use RouteBuilder::setExtensions()/getExtensions() instead.'
  185. );
  186. if ($extensions === null) {
  187. return $this->getExtensions();
  188. }
  189. $this->setExtensions($extensions);
  190. }
  191. /**
  192. * Set the extensions in this route builder's scope.
  193. *
  194. * Future routes connected in through this builder will have the connected
  195. * extensions applied. However, setting extensions does not modify existing routes.
  196. *
  197. * @param string|string[] $extensions The extensions to set.
  198. * @return $this
  199. */
  200. public function setExtensions($extensions)
  201. {
  202. $this->_extensions = (array)$extensions;
  203. return $this;
  204. }
  205. /**
  206. * Get the extensions in this route builder's scope.
  207. *
  208. * @return string[]
  209. */
  210. public function getExtensions()
  211. {
  212. return $this->_extensions;
  213. }
  214. /**
  215. * Add additional extensions to what is already in current scope
  216. *
  217. * @param string|string[] $extensions One or more extensions to add
  218. * @return void
  219. */
  220. public function addExtensions($extensions)
  221. {
  222. $extensions = array_merge($this->_extensions, (array)$extensions);
  223. $this->_extensions = array_unique($extensions);
  224. }
  225. /**
  226. * Get the path this scope is for.
  227. *
  228. * @return string
  229. */
  230. public function path()
  231. {
  232. $routeKey = strpos($this->_path, ':');
  233. if ($routeKey !== false) {
  234. return substr($this->_path, 0, $routeKey);
  235. }
  236. return $this->_path;
  237. }
  238. /**
  239. * Get the parameter names/values for this scope.
  240. *
  241. * @return array
  242. */
  243. public function params()
  244. {
  245. return $this->_params;
  246. }
  247. /**
  248. * Checks if there is already a route with a given name.
  249. *
  250. * @param string $name Name.
  251. * @return bool
  252. */
  253. public function nameExists($name)
  254. {
  255. return array_key_exists($name, $this->_collection->named());
  256. }
  257. /**
  258. * Get/set the name prefix for this scope.
  259. *
  260. * Modifying the name prefix will only change the prefix
  261. * used for routes connected after the prefix is changed.
  262. *
  263. * @param string|null $value Either the value to set or null.
  264. * @return string
  265. */
  266. public function namePrefix($value = null)
  267. {
  268. if ($value !== null) {
  269. $this->_namePrefix = $value;
  270. }
  271. return $this->_namePrefix;
  272. }
  273. /**
  274. * Generate REST resource routes for the given controller(s).
  275. *
  276. * A quick way to generate a default routes to a set of REST resources (controller(s)).
  277. *
  278. * ### Usage
  279. *
  280. * Connect resource routes for an app controller:
  281. *
  282. * ```
  283. * $routes->resources('Posts');
  284. * ```
  285. *
  286. * Connect resource routes for the Comments controller in the
  287. * Comments plugin:
  288. *
  289. * ```
  290. * Router::plugin('Comments', function ($routes) {
  291. * $routes->resources('Comments');
  292. * });
  293. * ```
  294. *
  295. * Plugins will create lower_case underscored resource routes. e.g
  296. * `/comments/comments`
  297. *
  298. * Connect resource routes for the Articles controller in the
  299. * Admin prefix:
  300. *
  301. * ```
  302. * Router::prefix('admin', function ($routes) {
  303. * $routes->resources('Articles');
  304. * });
  305. * ```
  306. *
  307. * Prefixes will create lower_case underscored resource routes. e.g
  308. * `/admin/posts`
  309. *
  310. * You can create nested resources by passing a callback in:
  311. *
  312. * ```
  313. * $routes->resources('Articles', function ($routes) {
  314. * $routes->resources('Comments');
  315. * });
  316. * ```
  317. *
  318. * The above would generate both resource routes for `/articles`, and `/articles/:article_id/comments`.
  319. * You can use the `map` option to connect additional resource methods:
  320. *
  321. * ```
  322. * $routes->resources('Articles', [
  323. * 'map' => ['deleteAll' => ['action' => 'deleteAll', 'method' => 'DELETE']]
  324. * ]);
  325. * ```
  326. *
  327. * In addition to the default routes, this would also connect a route for `/articles/delete_all`.
  328. * By default the path segment will match the key name. You can use the 'path' key inside the resource
  329. * definition to customize the path name.
  330. *
  331. * You can use the `inflect` option to change how path segments are generated:
  332. *
  333. * ```
  334. * $routes->resources('PaymentTypes', ['inflect' => 'dasherize']);
  335. * ```
  336. *
  337. * Will generate routes like `/payment-types` instead of `/payment_types`
  338. *
  339. * ### Options:
  340. *
  341. * - 'id' - The regular expression fragment to use when matching IDs. By default, matches
  342. * integer values and UUIDs.
  343. * - 'inflect' - Choose the inflection method used on the resource name. Defaults to 'underscore'.
  344. * - 'only' - Only connect the specific list of actions.
  345. * - 'actions' - Override the method names used for connecting actions.
  346. * - 'map' - Additional resource routes that should be connected. If you define 'only' and 'map',
  347. * make sure that your mapped methods are also in the 'only' list.
  348. * - 'prefix' - Define a routing prefix for the resource controller. If the current scope
  349. * defines a prefix, this prefix will be appended to it.
  350. * - 'connectOptions' - Custom options for connecting the routes.
  351. * - 'path' - Change the path so it doesn't match the resource name. E.g ArticlesController
  352. * is available at `/posts`
  353. *
  354. * @param string $name A controller name to connect resource routes for.
  355. * @param array|callable $options Options to use when generating REST routes, or a callback.
  356. * @param callable|null $callback An optional callback to be executed in a nested scope. Nested
  357. * scopes inherit the existing path and 'id' parameter.
  358. * @return void
  359. */
  360. public function resources($name, $options = [], $callback = null)
  361. {
  362. if (is_callable($options)) {
  363. $callback = $options;
  364. $options = [];
  365. }
  366. $options += [
  367. 'connectOptions' => [],
  368. 'inflect' => 'underscore',
  369. 'id' => static::ID . '|' . static::UUID,
  370. 'only' => [],
  371. 'actions' => [],
  372. 'map' => [],
  373. 'prefix' => null,
  374. 'path' => null,
  375. ];
  376. foreach ($options['map'] as $k => $mapped) {
  377. $options['map'][$k] += ['method' => 'GET', 'path' => $k, 'action' => ''];
  378. }
  379. $ext = null;
  380. if (!empty($options['_ext'])) {
  381. $ext = $options['_ext'];
  382. }
  383. $connectOptions = $options['connectOptions'];
  384. if (empty($options['path'])) {
  385. $method = $options['inflect'];
  386. $options['path'] = Inflector::$method($name);
  387. }
  388. $resourceMap = array_merge(static::$_resourceMap, $options['map']);
  389. $only = (array)$options['only'];
  390. if (empty($only)) {
  391. $only = array_keys($resourceMap);
  392. }
  393. $prefix = '';
  394. if ($options['prefix']) {
  395. $prefix = $options['prefix'];
  396. }
  397. if (isset($this->_params['prefix']) && $prefix) {
  398. $prefix = $this->_params['prefix'] . '/' . $prefix;
  399. }
  400. foreach ($resourceMap as $method => $params) {
  401. if (!in_array($method, $only, true)) {
  402. continue;
  403. }
  404. $action = $params['action'];
  405. if (isset($options['actions'][$method])) {
  406. $action = $options['actions'][$method];
  407. }
  408. $url = '/' . implode('/', array_filter([$options['path'], $params['path']]));
  409. $params = [
  410. 'controller' => $name,
  411. 'action' => $action,
  412. '_method' => $params['method'],
  413. ];
  414. if ($prefix) {
  415. $params['prefix'] = $prefix;
  416. }
  417. $routeOptions = $connectOptions + [
  418. 'id' => $options['id'],
  419. 'pass' => ['id'],
  420. '_ext' => $ext,
  421. ];
  422. $this->connect($url, $params, $routeOptions);
  423. }
  424. if (is_callable($callback)) {
  425. $idName = Inflector::singularize(Inflector::underscore($name)) . '_id';
  426. $path = '/' . $options['path'] . '/:' . $idName;
  427. $this->scope($path, [], $callback);
  428. }
  429. }
  430. /**
  431. * Create a route that only responds to GET requests.
  432. *
  433. * @param string $template The URL template to use.
  434. * @param array $target An array describing the target route parameters. These parameters
  435. * should indicate the plugin, prefix, controller, and action that this route points to.
  436. * @param string $name The name of the route.
  437. * @return \Cake\Routing\Route\Route
  438. */
  439. public function get($template, $target, $name = null)
  440. {
  441. return $this->_methodRoute('GET', $template, $target, $name);
  442. }
  443. /**
  444. * Create a route that only responds to POST requests.
  445. *
  446. * @param string $template The URL template to use.
  447. * @param array $target An array describing the target route parameters. These parameters
  448. * should indicate the plugin, prefix, controller, and action that this route points to.
  449. * @param string $name The name of the route.
  450. * @return \Cake\Routing\Route\Route
  451. */
  452. public function post($template, $target, $name = null)
  453. {
  454. return $this->_methodRoute('POST', $template, $target, $name);
  455. }
  456. /**
  457. * Create a route that only responds to PUT requests.
  458. *
  459. * @param string $template The URL template to use.
  460. * @param array $target An array describing the target route parameters. These parameters
  461. * should indicate the plugin, prefix, controller, and action that this route points to.
  462. * @param string $name The name of the route.
  463. * @return \Cake\Routing\Route\Route
  464. */
  465. public function put($template, $target, $name = null)
  466. {
  467. return $this->_methodRoute('PUT', $template, $target, $name);
  468. }
  469. /**
  470. * Create a route that only responds to PATCH requests.
  471. *
  472. * @param string $template The URL template to use.
  473. * @param array $target An array describing the target route parameters. These parameters
  474. * should indicate the plugin, prefix, controller, and action that this route points to.
  475. * @param string $name The name of the route.
  476. * @return \Cake\Routing\Route\Route
  477. */
  478. public function patch($template, $target, $name = null)
  479. {
  480. return $this->_methodRoute('PATCH', $template, $target, $name);
  481. }
  482. /**
  483. * Create a route that only responds to DELETE requests.
  484. *
  485. * @param string $template The URL template to use.
  486. * @param array $target An array describing the target route parameters. These parameters
  487. * should indicate the plugin, prefix, controller, and action that this route points to.
  488. * @param string $name The name of the route.
  489. * @return \Cake\Routing\Route\Route
  490. */
  491. public function delete($template, $target, $name = null)
  492. {
  493. return $this->_methodRoute('DELETE', $template, $target, $name);
  494. }
  495. /**
  496. * Create a route that only responds to HEAD requests.
  497. *
  498. * @param string $template The URL template to use.
  499. * @param array $target An array describing the target route parameters. These parameters
  500. * should indicate the plugin, prefix, controller, and action that this route points to.
  501. * @param string $name The name of the route.
  502. * @return \Cake\Routing\Route\Route
  503. */
  504. public function head($template, $target, $name = null)
  505. {
  506. return $this->_methodRoute('HEAD', $template, $target, $name);
  507. }
  508. /**
  509. * Create a route that only responds to OPTIONS requests.
  510. *
  511. * @param string $template The URL template to use.
  512. * @param array $target An array describing the target route parameters. These parameters
  513. * should indicate the plugin, prefix, controller, and action that this route points to.
  514. * @param string $name The name of the route.
  515. * @return \Cake\Routing\Route\Route
  516. */
  517. public function options($template, $target, $name = null)
  518. {
  519. return $this->_methodRoute('OPTIONS', $template, $target, $name);
  520. }
  521. /**
  522. * Helper to create routes that only respond to a single HTTP method.
  523. *
  524. * @param string $method The HTTP method name to match.
  525. * @param string $template The URL template to use.
  526. * @param array $target An array describing the target route parameters. These parameters
  527. * should indicate the plugin, prefix, controller, and action that this route points to.
  528. * @param string $name The name of the route.
  529. * @return \Cake\Routing\Route\Route
  530. */
  531. protected function _methodRoute($method, $template, $target, $name)
  532. {
  533. if ($name !== null) {
  534. $name = $this->_namePrefix . $name;
  535. }
  536. $options = [
  537. '_name' => $name,
  538. '_ext' => $this->_extensions,
  539. '_middleware' => $this->middleware,
  540. 'routeClass' => $this->_routeClass,
  541. ];
  542. $target = $this->parseDefaults($target);
  543. $target['_method'] = $method;
  544. $route = $this->_makeRoute($template, $target, $options);
  545. $this->_collection->add($route, $options);
  546. return $route;
  547. }
  548. /**
  549. * Load routes from a plugin.
  550. *
  551. * The routes file will have a local variable named `$routes` made available which contains
  552. * the current RouteBuilder instance.
  553. *
  554. * @param string $name The plugin name
  555. * @param string $file The routes file to load. Defaults to `routes.php`. This parameter
  556. * is deprecated and will be removed in 4.0
  557. * @return void
  558. * @throws \Cake\Core\Exception\MissingPluginException When the plugin has not been loaded.
  559. * @throws \InvalidArgumentException When the plugin does not have a routes file.
  560. */
  561. public function loadPlugin($name, $file = 'routes.php')
  562. {
  563. $plugins = Plugin::getCollection();
  564. if (!$plugins->has($name)) {
  565. throw new MissingPluginException(['plugin' => $name]);
  566. }
  567. $plugin = $plugins->get($name);
  568. // @deprecated This block should be removed in 4.0
  569. if ($file !== 'routes.php') {
  570. deprecationWarning(
  571. 'Loading plugin routes now uses the routes() hook method on the plugin class. ' .
  572. 'Loading non-standard files will be removed in 4.0'
  573. );
  574. $path = $plugin->getConfigPath() . DIRECTORY_SEPARATOR . $file;
  575. if (!file_exists($path)) {
  576. throw new InvalidArgumentException(sprintf(
  577. 'Cannot load routes for the plugin named %s. The %s file does not exist.',
  578. $name,
  579. $path
  580. ));
  581. }
  582. $routes = $this;
  583. include $path;
  584. return;
  585. }
  586. $plugin->routes($this);
  587. // Disable the routes hook to prevent duplicate route issues.
  588. $plugin->disable('routes');
  589. }
  590. /**
  591. * Connects a new Route.
  592. *
  593. * Routes are a way of connecting request URLs to objects in your application.
  594. * At their core routes are a set or regular expressions that are used to
  595. * match requests to destinations.
  596. *
  597. * Examples:
  598. *
  599. * ```
  600. * $routes->connect('/:controller/:action/*');
  601. * ```
  602. *
  603. * The first parameter will be used as a controller name while the second is
  604. * used as the action name. The '/*' syntax makes this route greedy in that
  605. * it will match requests like `/posts/index` as well as requests
  606. * like `/posts/edit/1/foo/bar`.
  607. *
  608. * ```
  609. * $routes->connect('/home-page', ['controller' => 'Pages', 'action' => 'display', 'home']);
  610. * ```
  611. *
  612. * The above shows the use of route parameter defaults. And providing routing
  613. * parameters for a static route.
  614. *
  615. * ```
  616. * $routes->connect(
  617. * '/:lang/:controller/:action/:id',
  618. * [],
  619. * ['id' => '[0-9]+', 'lang' => '[a-z]{3}']
  620. * );
  621. * ```
  622. *
  623. * Shows connecting a route with custom route parameters as well as
  624. * providing patterns for those parameters. Patterns for routing parameters
  625. * do not need capturing groups, as one will be added for each route params.
  626. *
  627. * $options offers several 'special' keys that have special meaning
  628. * in the $options array.
  629. *
  630. * - `routeClass` is used to extend and change how individual routes parse requests
  631. * and handle reverse routing, via a custom routing class.
  632. * Ex. `'routeClass' => 'SlugRoute'`
  633. * - `pass` is used to define which of the routed parameters should be shifted
  634. * into the pass array. Adding a parameter to pass will remove it from the
  635. * regular route array. Ex. `'pass' => ['slug']`.
  636. * - `persist` is used to define which route parameters should be automatically
  637. * included when generating new URLs. You can override persistent parameters
  638. * by redefining them in a URL or remove them by setting the parameter to `false`.
  639. * Ex. `'persist' => ['lang']`
  640. * - `multibytePattern` Set to true to enable multibyte pattern support in route
  641. * parameter patterns.
  642. * - `_name` is used to define a specific name for routes. This can be used to optimize
  643. * reverse routing lookups. If undefined a name will be generated for each
  644. * connected route.
  645. * - `_ext` is an array of filename extensions that will be parsed out of the url if present.
  646. * See {@link \Cake\Routing\RouteCollection::setExtensions()}.
  647. * - `_method` Only match requests with specific HTTP verbs.
  648. *
  649. * Example of using the `_method` condition:
  650. *
  651. * ```
  652. * $routes->connect('/tasks', ['controller' => 'Tasks', 'action' => 'index', '_method' => 'GET']);
  653. * ```
  654. *
  655. * The above route will only be matched for GET requests. POST requests will fail to match this route.
  656. *
  657. * @param string $route A string describing the template of the route
  658. * @param array|string $defaults An array describing the default route parameters. These parameters will be used by default
  659. * and can supply routing parameters that are not dynamic. See above.
  660. * @param array $options An array matching the named elements in the route to regular expressions which that
  661. * element should match. Also contains additional parameters such as which routed parameters should be
  662. * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a
  663. * custom routing class.
  664. * @return \Cake\Routing\Route\Route
  665. * @throws \InvalidArgumentException
  666. * @throws \BadMethodCallException
  667. */
  668. public function connect($route, $defaults = [], array $options = [])
  669. {
  670. $defaults = $this->parseDefaults($defaults);
  671. if (empty($options['_ext'])) {
  672. $options['_ext'] = $this->_extensions;
  673. }
  674. if (empty($options['routeClass'])) {
  675. $options['routeClass'] = $this->_routeClass;
  676. }
  677. if (isset($options['_name']) && $this->_namePrefix) {
  678. $options['_name'] = $this->_namePrefix . $options['_name'];
  679. }
  680. if (empty($options['_middleware'])) {
  681. $options['_middleware'] = $this->middleware;
  682. }
  683. $route = $this->_makeRoute($route, $defaults, $options);
  684. $this->_collection->add($route, $options);
  685. return $route;
  686. }
  687. /**
  688. * Parse the defaults if they're a string
  689. *
  690. * @param string|array $defaults Defaults array from the connect() method.
  691. * @return string|array
  692. */
  693. protected static function parseDefaults($defaults)
  694. {
  695. if (!is_string($defaults)) {
  696. return $defaults;
  697. }
  698. $regex = '/(?:(?<plugin>[a-zA-Z0-9\/]*)\.)?(?<prefix>[a-zA-Z0-9\/]*?)' .
  699. '(?:\/)?(?<controller>[a-zA-Z0-9]*):{2}(?<action>[a-zA-Z0-9_]*)/i';
  700. if (preg_match($regex, $defaults, $matches)) {
  701. foreach ($matches as $key => $value) {
  702. // Remove numeric keys and empty values.
  703. if (is_int($key) || $value === '' || $value === '::') {
  704. unset($matches[$key]);
  705. }
  706. }
  707. $length = count($matches);
  708. if (isset($matches['prefix'])) {
  709. $matches['prefix'] = strtolower($matches['prefix']);
  710. }
  711. if ($length >= 2 || $length <= 4) {
  712. return $matches;
  713. }
  714. }
  715. throw new RuntimeException("Could not parse `{$defaults}` route destination string.");
  716. }
  717. /**
  718. * Create a route object, or return the provided object.
  719. *
  720. * @param string|\Cake\Routing\Route\Route $route The route template or route object.
  721. * @param array $defaults Default parameters.
  722. * @param array $options Additional options parameters.
  723. * @return \Cake\Routing\Route\Route
  724. * @throws \InvalidArgumentException when route class or route object is invalid.
  725. * @throws \BadMethodCallException when the route to make conflicts with the current scope
  726. */
  727. protected function _makeRoute($route, $defaults, $options)
  728. {
  729. if (is_string($route)) {
  730. $routeClass = App::className($options['routeClass'], 'Routing/Route');
  731. if ($routeClass === false) {
  732. throw new InvalidArgumentException(sprintf(
  733. 'Cannot find route class %s',
  734. $options['routeClass']
  735. ));
  736. }
  737. $route = str_replace('//', '/', $this->_path . $route);
  738. if ($route !== '/') {
  739. $route = rtrim($route, '/');
  740. }
  741. foreach ($this->_params as $param => $val) {
  742. if (isset($defaults[$param]) && $param !== 'prefix' && $defaults[$param] !== $val) {
  743. $msg = 'You cannot define routes that conflict with the scope. ' .
  744. 'Scope had %s = %s, while route had %s = %s';
  745. throw new BadMethodCallException(sprintf(
  746. $msg,
  747. $param,
  748. $val,
  749. $param,
  750. $defaults[$param]
  751. ));
  752. }
  753. }
  754. $defaults += $this->_params + ['plugin' => null];
  755. if (!isset($defaults['action']) && !isset($options['action'])) {
  756. $defaults['action'] = 'index';
  757. }
  758. $route = new $routeClass($route, $defaults, $options);
  759. }
  760. if ($route instanceof Route) {
  761. return $route;
  762. }
  763. throw new InvalidArgumentException(
  764. 'Route class not found, or route class is not a subclass of Cake\Routing\Route\Route'
  765. );
  766. }
  767. /**
  768. * Connects a new redirection Route in the router.
  769. *
  770. * Redirection routes are different from normal routes as they perform an actual
  771. * header redirection if a match is found. The redirection can occur within your
  772. * application or redirect to an outside location.
  773. *
  774. * Examples:
  775. *
  776. * ```
  777. * $routes->redirect('/home/*', ['controller' => 'posts', 'action' => 'view']);
  778. * ```
  779. *
  780. * Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the
  781. * redirect destination allows you to use other routes to define where a URL string should be redirected to.
  782. *
  783. * ```
  784. * $routes->redirect('/posts/*', 'http://google.com', ['status' => 302]);
  785. * ```
  786. *
  787. * Redirects /posts/* to http://google.com with a HTTP status of 302
  788. *
  789. * ### Options:
  790. *
  791. * - `status` Sets the HTTP status (default 301)
  792. * - `persist` Passes the params to the redirected route, if it can. This is useful with greedy routes,
  793. * routes that end in `*` are greedy. As you can remap URLs and not lose any passed args.
  794. *
  795. * @param string $route A string describing the template of the route
  796. * @param array|string $url A URL to redirect to. Can be a string or a Cake array-based URL
  797. * @param array $options An array matching the named elements in the route to regular expressions which that
  798. * element should match. Also contains additional parameters such as which routed parameters should be
  799. * shifted into the passed arguments. As well as supplying patterns for routing parameters.
  800. * @return \Cake\Routing\Route\Route|\Cake\Routing\Route\RedirectRoute
  801. */
  802. public function redirect($route, $url, array $options = [])
  803. {
  804. if (!isset($options['routeClass'])) {
  805. $options['routeClass'] = 'Cake\Routing\Route\RedirectRoute';
  806. }
  807. if (is_string($url)) {
  808. $url = ['redirect' => $url];
  809. }
  810. return $this->connect($route, $url, $options);
  811. }
  812. /**
  813. * Add prefixed routes.
  814. *
  815. * This method creates a scoped route collection that includes
  816. * relevant prefix information.
  817. *
  818. * The $name parameter is used to generate the routing parameter name.
  819. * For example a path of `admin` would result in `'prefix' => 'admin'` being
  820. * applied to all connected routes.
  821. *
  822. * You can re-open a prefix as many times as necessary, as well as nest prefixes.
  823. * Nested prefixes will result in prefix values like `admin/api` which translates
  824. * to the `Controller\Admin\Api\` namespace.
  825. *
  826. * If you need to have prefix with dots, eg: '/api/v1.0', use 'path' key
  827. * for $params argument:
  828. *
  829. * ```
  830. * $route->prefix('api', function($route) {
  831. * $route->prefix('v10', ['path' => '/v1.0'], function($route) {
  832. * // Translates to `Controller\Api\V10\` namespace
  833. * });
  834. * });
  835. * ```
  836. *
  837. * @param string $name The prefix name to use.
  838. * @param array|callable $params An array of routing defaults to add to each connected route.
  839. * If you have no parameters, this argument can be a callable.
  840. * @param callable|null $callback The callback to invoke that builds the prefixed routes.
  841. * @return void
  842. * @throws \InvalidArgumentException If a valid callback is not passed
  843. */
  844. public function prefix($name, $params = [], callable $callback = null)
  845. {
  846. if ($callback === null) {
  847. if (!is_callable($params)) {
  848. throw new InvalidArgumentException('A valid callback is expected');
  849. }
  850. $callback = $params;
  851. $params = [];
  852. }
  853. $name = Inflector::underscore($name);
  854. $path = '/' . $name;
  855. if (isset($params['path'])) {
  856. $path = $params['path'];
  857. unset($params['path']);
  858. }
  859. if (isset($this->_params['prefix'])) {
  860. $name = $this->_params['prefix'] . '/' . $name;
  861. }
  862. $params = array_merge($params, ['prefix' => $name]);
  863. $this->scope($path, $params, $callback);
  864. }
  865. /**
  866. * Add plugin routes.
  867. *
  868. * This method creates a new scoped route collection that includes
  869. * relevant plugin information.
  870. *
  871. * The plugin name will be inflected to the underscore version to create
  872. * the routing path. If you want a custom path name, use the `path` option.
  873. *
  874. * Routes connected in the scoped collection will have the correct path segment
  875. * prepended, and have a matching plugin routing key set.
  876. *
  877. * @param string $name The plugin name to build routes for
  878. * @param array|callable $options Either the options to use, or a callback
  879. * @param callable|null $callback The callback to invoke that builds the plugin routes
  880. * Only required when $options is defined.
  881. * @return void
  882. */
  883. public function plugin($name, $options = [], $callback = null)
  884. {
  885. if ($callback === null) {
  886. $callback = $options;
  887. $options = [];
  888. }
  889. $params = ['plugin' => $name] + $this->_params;
  890. if (empty($options['path'])) {
  891. $options['path'] = '/' . Inflector::underscore($name);
  892. }
  893. $this->scope($options['path'], $params, $callback);
  894. }
  895. /**
  896. * Create a new routing scope.
  897. *
  898. * Scopes created with this method will inherit the properties of the scope they are
  899. * added to. This means that both the current path and parameters will be appended
  900. * to the supplied parameters.
  901. *
  902. * @param string $path The path to create a scope for.
  903. * @param array|callable $params Either the parameters to add to routes, or a callback.
  904. * @param callable|null $callback The callback to invoke that builds the plugin routes.
  905. * Only required when $params is defined.
  906. * @return void
  907. * @throws \InvalidArgumentException when there is no callable parameter.
  908. */
  909. public function scope($path, $params, $callback = null)
  910. {
  911. if (is_callable($params)) {
  912. $callback = $params;
  913. $params = [];
  914. }
  915. if (!is_callable($callback)) {
  916. $msg = 'Need a callable function/object to connect routes.';
  917. throw new InvalidArgumentException($msg);
  918. }
  919. if ($this->_path !== '/') {
  920. $path = $this->_path . $path;
  921. }
  922. $namePrefix = $this->_namePrefix;
  923. if (isset($params['_namePrefix'])) {
  924. $namePrefix .= $params['_namePrefix'];
  925. }
  926. unset($params['_namePrefix']);
  927. $params += $this->_params;
  928. $builder = new static($this->_collection, $path, $params, [
  929. 'routeClass' => $this->_routeClass,
  930. 'extensions' => $this->_extensions,
  931. 'namePrefix' => $namePrefix,
  932. 'middleware' => $this->middleware,
  933. ]);
  934. $callback($builder);
  935. }
  936. /**
  937. * Connect the `/:controller` and `/:controller/:action/*` fallback routes.
  938. *
  939. * This is a shortcut method for connecting fallback routes in a given scope.
  940. *
  941. * @param string|null $routeClass the route class to use, uses the default routeClass
  942. * if not specified
  943. * @return void
  944. */
  945. public function fallbacks($routeClass = null)
  946. {
  947. $routeClass = $routeClass ?: $this->_routeClass;
  948. $this->connect('/:controller', ['action' => 'index'], compact('routeClass'));
  949. $this->connect('/:controller/:action/*', [], compact('routeClass'));
  950. }
  951. /**
  952. * Register a middleware with the RouteCollection.
  953. *
  954. * Once middleware has been registered, it can be applied to the current routing
  955. * scope or any child scopes that share the same RouteCollection.
  956. *
  957. * @param string $name The name of the middleware. Used when applying middleware to a scope.
  958. * @param callable|string $middleware The middleware callable or class name to register.
  959. * @return $this
  960. * @see \Cake\Routing\RouteCollection
  961. */
  962. public function registerMiddleware($name, $middleware)
  963. {
  964. $this->_collection->registerMiddleware($name, $middleware);
  965. return $this;
  966. }
  967. /**
  968. * Apply a middleware to the current route scope.
  969. *
  970. * Requires middleware to be registered via `registerMiddleware()`
  971. *
  972. * @param string ...$names The names of the middleware to apply to the current scope.
  973. * @return $this
  974. * @throws \RuntimeException
  975. * @see \Cake\Routing\RouteCollection::addMiddlewareToScope()
  976. */
  977. public function applyMiddleware(...$names)
  978. {
  979. foreach ($names as $name) {
  980. if (!$this->_collection->middlewareExists($name)) {
  981. $message = "Cannot apply '$name' middleware or middleware group. " .
  982. 'Use registerMiddleware() to register middleware.';
  983. throw new RuntimeException($message);
  984. }
  985. }
  986. $this->middleware = array_unique(array_merge($this->middleware, $names));
  987. return $this;
  988. }
  989. /**
  990. * Apply a set of middleware to a group
  991. *
  992. * @param string $name Name of the middleware group
  993. * @param string[] $middlewareNames Names of the middleware
  994. * @return $this
  995. */
  996. public function middlewareGroup($name, array $middlewareNames)
  997. {
  998. $this->_collection->middlewareGroup($name, $middlewareNames);
  999. return $this;
  1000. }
  1001. }