RouteBuilderTest.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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\Test\TestCase\Routing;
  16. use Cake\Core\Plugin;
  17. use Cake\Routing\RouteBuilder;
  18. use Cake\Routing\RouteCollection;
  19. use Cake\Routing\Router;
  20. use Cake\Routing\Route\InflectedRoute;
  21. use Cake\Routing\Route\RedirectRoute;
  22. use Cake\Routing\Route\Route;
  23. use Cake\TestSuite\TestCase;
  24. /**
  25. * RouteBuilder test case
  26. */
  27. class RouteBuilderTest extends TestCase
  28. {
  29. /**
  30. * Setup method
  31. *
  32. * @return void
  33. */
  34. public function setUp()
  35. {
  36. parent::setUp();
  37. $this->collection = new RouteCollection();
  38. }
  39. /**
  40. * Teardown method
  41. *
  42. * @return void
  43. */
  44. public function tearDown()
  45. {
  46. parent::tearDown();
  47. Plugin::unload('TestPlugin');
  48. }
  49. /**
  50. * Test path()
  51. *
  52. * @return void
  53. */
  54. public function testPath()
  55. {
  56. $routes = new RouteBuilder($this->collection, '/some/path');
  57. $this->assertEquals('/some/path', $routes->path());
  58. $routes = new RouteBuilder($this->collection, '/:book_id');
  59. $this->assertEquals('/', $routes->path());
  60. $routes = new RouteBuilder($this->collection, '/path/:book_id');
  61. $this->assertEquals('/path/', $routes->path());
  62. $routes = new RouteBuilder($this->collection, '/path/book:book_id');
  63. $this->assertEquals('/path/book', $routes->path());
  64. }
  65. /**
  66. * Test params()
  67. *
  68. * @return void
  69. */
  70. public function testParams()
  71. {
  72. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  73. $this->assertEquals(['prefix' => 'api'], $routes->params());
  74. }
  75. /**
  76. * Test getting connected routes.
  77. *
  78. * @return void
  79. */
  80. public function testRoutes()
  81. {
  82. $routes = new RouteBuilder($this->collection, '/l');
  83. $routes->connect('/:controller', ['action' => 'index']);
  84. $routes->connect('/:controller/:action/*');
  85. $all = $this->collection->routes();
  86. $this->assertCount(2, $all);
  87. $this->assertInstanceOf(Route::class, $all[0]);
  88. $this->assertInstanceOf(Route::class, $all[1]);
  89. }
  90. /**
  91. * Test setting default route class
  92. *
  93. * @return void
  94. */
  95. public function testRouteClass()
  96. {
  97. $routes = new RouteBuilder(
  98. $this->collection,
  99. '/l',
  100. [],
  101. ['routeClass' => 'InflectedRoute']
  102. );
  103. $routes->connect('/:controller', ['action' => 'index']);
  104. $routes->connect('/:controller/:action/*');
  105. $all = $this->collection->routes();
  106. $this->assertInstanceOf(InflectedRoute::class, $all[0]);
  107. $this->assertInstanceOf(InflectedRoute::class, $all[1]);
  108. $this->collection = new RouteCollection();
  109. $routes = new RouteBuilder($this->collection, '/l');
  110. $this->assertSame($routes, $routes->setRouteClass('TestApp\Routing\Route\DashedRoute'));
  111. $this->assertSame('TestApp\Routing\Route\DashedRoute', $routes->getRouteClass());
  112. $routes->connect('/:controller', ['action' => 'index']);
  113. $all = $this->collection->routes();
  114. $this->assertInstanceOf('TestApp\Routing\Route\DashedRoute', $all[0]);
  115. }
  116. /**
  117. * Test connecting an instance routes.
  118. *
  119. * @return void
  120. */
  121. public function testConnectInstance()
  122. {
  123. $routes = new RouteBuilder($this->collection, '/l', ['prefix' => 'api']);
  124. $route = new Route('/:controller');
  125. $this->assertSame($route, $routes->connect($route));
  126. $result = $this->collection->routes()[0];
  127. $this->assertSame($route, $result);
  128. }
  129. /**
  130. * Test connecting basic routes.
  131. *
  132. * @return void
  133. */
  134. public function testConnectBasic()
  135. {
  136. $routes = new RouteBuilder($this->collection, '/l', ['prefix' => 'api']);
  137. $route = $routes->connect('/:controller');
  138. $this->assertInstanceOf(Route::class, $route);
  139. $this->assertSame($route, $this->collection->routes()[0]);
  140. $this->assertEquals('/l/:controller', $route->template);
  141. $expected = ['prefix' => 'api', 'action' => 'index', 'plugin' => null];
  142. $this->assertEquals($expected, $route->defaults);
  143. }
  144. /**
  145. * Test that compiling a route results in an trailing / optional pattern.
  146. *
  147. * @return void
  148. */
  149. public function testConnectTrimTrailingSlash()
  150. {
  151. $routes = new RouteBuilder($this->collection, '/articles', ['controller' => 'Articles']);
  152. $routes->connect('/', ['action' => 'index']);
  153. $expected = [
  154. 'plugin' => null,
  155. 'controller' => 'Articles',
  156. 'action' => 'index',
  157. 'pass' => [],
  158. '_matchedRoute' => '/articles',
  159. ];
  160. $this->assertEquals($expected, $this->collection->parse('/articles'));
  161. $this->assertEquals($expected, $this->collection->parse('/articles/'));
  162. }
  163. /**
  164. * Test if a route name already exist
  165. *
  166. * @return void
  167. */
  168. public function testNameExists()
  169. {
  170. $routes = new RouteBuilder($this->collection, '/l', ['prefix' => 'api']);
  171. $this->assertFalse($routes->nameExists('myRouteName'));
  172. $routes->connect('myRouteUrl', ['action' => 'index'], ['_name' => 'myRouteName']);
  173. $this->assertTrue($routes->nameExists('myRouteName'));
  174. }
  175. /**
  176. * Test setExtensions() and getExtensions().
  177. *
  178. * @return void
  179. */
  180. public function testExtensions()
  181. {
  182. $routes = new RouteBuilder($this->collection, '/l');
  183. $this->assertSame($routes, $routes->setExtensions(['html']));
  184. $this->assertSame(['html'], $routes->getExtensions());
  185. }
  186. /**
  187. * Test extensions being connected to routes.
  188. *
  189. * @return void
  190. */
  191. public function testConnectExtensions()
  192. {
  193. $routes = new RouteBuilder(
  194. $this->collection,
  195. '/l',
  196. [],
  197. ['extensions' => ['json']]
  198. );
  199. $this->assertEquals(['json'], $routes->getExtensions());
  200. $routes->connect('/:controller');
  201. $route = $this->collection->routes()[0];
  202. $this->assertEquals(['json'], $route->options['_ext']);
  203. $routes->setExtensions(['xml', 'json']);
  204. $routes->connect('/:controller/:action');
  205. $new = $this->collection->routes()[1];
  206. $this->assertEquals(['json'], $route->options['_ext']);
  207. $this->assertEquals(['xml', 'json'], $new->options['_ext']);
  208. }
  209. /**
  210. * Test adding additional extensions will be merged with current.
  211. *
  212. * @return void
  213. */
  214. public function testConnectExtensionsAdd()
  215. {
  216. $routes = new RouteBuilder(
  217. $this->collection,
  218. '/l',
  219. [],
  220. ['extensions' => ['json']]
  221. );
  222. $this->assertEquals(['json'], $routes->getExtensions());
  223. $routes->addExtensions(['xml']);
  224. $this->assertEquals(['json', 'xml'], $routes->getExtensions());
  225. $routes->addExtensions('csv');
  226. $this->assertEquals(['json', 'xml', 'csv'], $routes->getExtensions());
  227. }
  228. /**
  229. * test that setExtensions() accepts a string.
  230. *
  231. * @return void
  232. */
  233. public function testExtensionsString()
  234. {
  235. $routes = new RouteBuilder($this->collection, '/l');
  236. $routes->setExtensions('json');
  237. $this->assertEquals(['json'], $routes->getExtensions());
  238. }
  239. /**
  240. * Test error on invalid route class
  241. *
  242. * @return void
  243. */
  244. public function testConnectErrorInvalidRouteClass()
  245. {
  246. $this->expectException(\InvalidArgumentException::class);
  247. $this->expectExceptionMessage('Route class not found, or route class is not a subclass of');
  248. $routes = new RouteBuilder(
  249. $this->collection,
  250. '/l',
  251. [],
  252. ['extensions' => ['json']]
  253. );
  254. $routes->connect('/:controller', [], ['routeClass' => '\StdClass']);
  255. }
  256. /**
  257. * Test conflicting parameters raises an exception.
  258. *
  259. * @return void
  260. */
  261. public function testConnectConflictingParameters()
  262. {
  263. $this->expectException(\BadMethodCallException::class);
  264. $this->expectExceptionMessage('You cannot define routes that conflict with the scope.');
  265. $routes = new RouteBuilder($this->collection, '/admin', ['plugin' => 'TestPlugin']);
  266. $routes->connect('/', ['plugin' => 'TestPlugin2', 'controller' => 'Dashboard', 'action' => 'view']);
  267. }
  268. /**
  269. * Test connecting redirect routes.
  270. *
  271. * @return void
  272. */
  273. public function testRedirect()
  274. {
  275. $routes = new RouteBuilder($this->collection, '/');
  276. $routes->redirect('/p/:id', ['controller' => 'posts', 'action' => 'view'], ['status' => 301]);
  277. $route = $this->collection->routes()[0];
  278. $this->assertInstanceOf(RedirectRoute::class, $route);
  279. $routes->redirect('/old', '/forums', ['status' => 301]);
  280. $route = $this->collection->routes()[1];
  281. $this->assertInstanceOf(RedirectRoute::class, $route);
  282. $this->assertEquals('/forums', $route->redirect[0]);
  283. }
  284. /**
  285. * Test using a custom route class for redirect routes.
  286. *
  287. * @return void
  288. */
  289. public function testRedirectWithCustomRouteClass()
  290. {
  291. $routes = new RouteBuilder($this->collection, '/');
  292. $routes->redirect('/old', '/forums', ['status' => 301, 'routeClass' => 'InflectedRoute']);
  293. $route = $this->collection->routes()[0];
  294. $this->assertInstanceOf(InflectedRoute::class, $route);
  295. }
  296. /**
  297. * Test creating sub-scopes with prefix()
  298. *
  299. * @return void
  300. */
  301. public function testPrefix()
  302. {
  303. $routes = new RouteBuilder($this->collection, '/path', ['key' => 'value']);
  304. $res = $routes->prefix('admin', ['param' => 'value'], function ($r) {
  305. $this->assertInstanceOf(RouteBuilder::class, $r);
  306. $this->assertCount(0, $this->collection->routes());
  307. $this->assertEquals('/path/admin', $r->path());
  308. $this->assertEquals(['prefix' => 'admin', 'key' => 'value', 'param' => 'value'], $r->params());
  309. });
  310. $this->assertNull($res);
  311. }
  312. /**
  313. * Test creating sub-scopes with prefix()
  314. *
  315. * @return void
  316. */
  317. public function testPrefixWithNoParams()
  318. {
  319. $routes = new RouteBuilder($this->collection, '/path', ['key' => 'value']);
  320. $res = $routes->prefix('admin', function ($r) {
  321. $this->assertInstanceOf(RouteBuilder::class, $r);
  322. $this->assertCount(0, $this->collection->routes());
  323. $this->assertEquals('/path/admin', $r->path());
  324. $this->assertEquals(['prefix' => 'admin', 'key' => 'value'], $r->params());
  325. });
  326. $this->assertNull($res);
  327. }
  328. /**
  329. * Test creating sub-scopes with prefix()
  330. *
  331. * @return void
  332. */
  333. public function testNestedPrefix()
  334. {
  335. $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'admin']);
  336. $res = $routes->prefix('api', ['_namePrefix' => 'api:'], function ($r) {
  337. $this->assertEquals('/admin/api', $r->path());
  338. $this->assertEquals(['prefix' => 'admin/api'], $r->params());
  339. $this->assertEquals('api:', $r->namePrefix());
  340. });
  341. $this->assertNull($res);
  342. }
  343. /**
  344. * Test creating sub-scopes with prefix()
  345. *
  346. * @return void
  347. */
  348. public function testPathWithDotInPrefix()
  349. {
  350. $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'admin']);
  351. $res = $routes->prefix('api', function ($r) {
  352. $r->prefix('v10', ['path' => '/v1.0'], function ($r2) {
  353. $this->assertEquals('/admin/api/v1.0', $r2->path());
  354. $this->assertEquals(['prefix' => 'admin/api/v10'], $r2->params());
  355. $r2->prefix('b1', ['path' => '/beta.1'], function ($r3) {
  356. $this->assertEquals('/admin/api/v1.0/beta.1', $r3->path());
  357. $this->assertEquals(['prefix' => 'admin/api/v10/b1'], $r3->params());
  358. });
  359. });
  360. });
  361. $this->assertNull($res);
  362. }
  363. /**
  364. * Test creating sub-scopes with plugin()
  365. *
  366. * @return void
  367. */
  368. public function testNestedPlugin()
  369. {
  370. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  371. $res = $routes->plugin('Contacts', function ($r) {
  372. $this->assertEquals('/b/contacts', $r->path());
  373. $this->assertEquals(['plugin' => 'Contacts', 'key' => 'value'], $r->params());
  374. $r->connect('/:controller');
  375. $route = $this->collection->routes()[0];
  376. $this->assertEquals(
  377. ['key' => 'value', 'plugin' => 'Contacts', 'action' => 'index'],
  378. $route->defaults
  379. );
  380. });
  381. $this->assertNull($res);
  382. }
  383. /**
  384. * Test creating sub-scopes with plugin() + path option
  385. *
  386. * @return void
  387. */
  388. public function testNestedPluginPathOption()
  389. {
  390. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  391. $routes->plugin('Contacts', ['path' => '/people'], function ($r) {
  392. $this->assertEquals('/b/people', $r->path());
  393. $this->assertEquals(['plugin' => 'Contacts', 'key' => 'value'], $r->params());
  394. });
  395. }
  396. /**
  397. * Test connecting resources.
  398. *
  399. * @return void
  400. */
  401. public function testResources()
  402. {
  403. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  404. $routes->resources('Articles', ['_ext' => 'json']);
  405. $all = $this->collection->routes();
  406. $this->assertCount(5, $all);
  407. $this->assertEquals('/api/articles', $all[0]->template);
  408. $this->assertEquals(
  409. ['controller', 'action', '_method', 'prefix', 'plugin'],
  410. array_keys($all[0]->defaults)
  411. );
  412. $this->assertEquals('json', $all[0]->options['_ext']);
  413. $this->assertEquals('Articles', $all[0]->defaults['controller']);
  414. }
  415. /**
  416. * Test connecting resources with a path
  417. *
  418. * @return void
  419. */
  420. public function testResourcesPathOption()
  421. {
  422. $routes = new RouteBuilder($this->collection, '/api');
  423. $routes->resources('Articles', ['path' => 'posts'], function ($routes) {
  424. $routes->resources('Comments');
  425. });
  426. $all = $this->collection->routes();
  427. $this->assertEquals('Articles', $all[0]->defaults['controller']);
  428. $this->assertEquals('/api/posts', $all[0]->template);
  429. $this->assertEquals('/api/posts/:id', $all[2]->template);
  430. $this->assertEquals(
  431. '/api/posts/:article_id/comments',
  432. $all[6]->template,
  433. 'parameter name should reflect resource name'
  434. );
  435. }
  436. /**
  437. * Test connecting resources with a prefix
  438. *
  439. * @return void
  440. */
  441. public function testResourcesPrefix()
  442. {
  443. $routes = new RouteBuilder($this->collection, '/api');
  444. $routes->resources('Articles', ['prefix' => 'rest']);
  445. $all = $this->collection->routes();
  446. $this->assertEquals('rest', $all[0]->defaults['prefix']);
  447. }
  448. /**
  449. * Test that resource prefixes work within a prefixed scope.
  450. *
  451. * @return void
  452. */
  453. public function testResourcesNestedPrefix()
  454. {
  455. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  456. $routes->resources('Articles', ['prefix' => 'rest']);
  457. $all = $this->collection->routes();
  458. $this->assertCount(5, $all);
  459. $this->assertEquals('/api/articles', $all[0]->template);
  460. foreach ($all as $route) {
  461. $this->assertEquals('api/rest', $route->defaults['prefix']);
  462. $this->assertEquals('Articles', $route->defaults['controller']);
  463. }
  464. }
  465. /**
  466. * Test connecting resources with the inflection option
  467. *
  468. * @return void
  469. */
  470. public function testResourcesInflection()
  471. {
  472. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  473. $routes->resources('BlogPosts', ['_ext' => 'json', 'inflect' => 'dasherize']);
  474. $all = $this->collection->routes();
  475. $this->assertCount(5, $all);
  476. $this->assertEquals('/api/blog-posts', $all[0]->template);
  477. $this->assertEquals(
  478. ['controller', 'action', '_method', 'prefix', 'plugin'],
  479. array_keys($all[0]->defaults)
  480. );
  481. $this->assertEquals('BlogPosts', $all[0]->defaults['controller']);
  482. }
  483. /**
  484. * Test connecting nested resources with the inflection option
  485. *
  486. * @return void
  487. */
  488. public function testResourcesNestedInflection()
  489. {
  490. $routes = new RouteBuilder($this->collection, '/api');
  491. $routes->resources(
  492. 'NetworkObjects',
  493. ['inflect' => 'dasherize'],
  494. function ($routes) {
  495. $routes->resources('Attributes');
  496. }
  497. );
  498. $all = $this->collection->routes();
  499. $this->assertCount(10, $all);
  500. $this->assertEquals('/api/network-objects', $all[0]->template);
  501. $this->assertEquals('/api/network-objects/:id', $all[2]->template);
  502. $this->assertEquals('/api/network-objects/:network_object_id/attributes', $all[5]->template);
  503. }
  504. /**
  505. * Test connecting resources with additional mappings
  506. *
  507. * @return void
  508. */
  509. public function testResourcesMappings()
  510. {
  511. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  512. $routes->resources('Articles', [
  513. '_ext' => 'json',
  514. 'map' => [
  515. 'delete_all' => ['action' => 'deleteAll', 'method' => 'DELETE'],
  516. 'update_many' => ['action' => 'updateAll', 'method' => 'DELETE', 'path' => '/updateAll'],
  517. ]
  518. ]);
  519. $all = $this->collection->routes();
  520. $this->assertCount(7, $all);
  521. $this->assertEquals('/api/articles/delete_all', $all[5]->template, 'Path defaults to key name.');
  522. $this->assertEquals(
  523. ['controller', 'action', '_method', 'prefix', 'plugin'],
  524. array_keys($all[5]->defaults)
  525. );
  526. $this->assertEquals('Articles', $all[5]->defaults['controller']);
  527. $this->assertEquals('deleteAll', $all[5]->defaults['action']);
  528. $this->assertEquals('/api/articles/updateAll', $all[6]->template, 'Explicit path option');
  529. $this->assertEquals(
  530. ['controller', 'action', '_method', 'prefix', 'plugin'],
  531. array_keys($all[6]->defaults)
  532. );
  533. $this->assertEquals('Articles', $all[6]->defaults['controller']);
  534. $this->assertEquals('updateAll', $all[6]->defaults['action']);
  535. }
  536. /**
  537. * Test connecting resources.
  538. *
  539. * @return void
  540. */
  541. public function testResourcesInScope()
  542. {
  543. Router::scope('/api', ['prefix' => 'api'], function ($routes) {
  544. $routes->setExtensions(['json']);
  545. $routes->resources('Articles');
  546. });
  547. $url = Router::url([
  548. 'prefix' => 'api',
  549. 'controller' => 'Articles',
  550. 'action' => 'edit',
  551. '_method' => 'PUT',
  552. 'id' => 99
  553. ]);
  554. $this->assertEquals('/api/articles/99', $url);
  555. $url = Router::url([
  556. 'prefix' => 'api',
  557. 'controller' => 'Articles',
  558. 'action' => 'edit',
  559. '_method' => 'PUT',
  560. '_ext' => 'json',
  561. 'id' => 99
  562. ]);
  563. $this->assertEquals('/api/articles/99.json', $url);
  564. }
  565. /**
  566. * Test resource parsing.
  567. *
  568. * @return void
  569. */
  570. public function testResourcesParsing()
  571. {
  572. $routes = new RouteBuilder($this->collection, '/');
  573. $routes->resources('Articles');
  574. $_SERVER['REQUEST_METHOD'] = 'GET';
  575. $result = $this->collection->parse('/articles');
  576. $this->assertEquals('Articles', $result['controller']);
  577. $this->assertEquals('index', $result['action']);
  578. $this->assertEquals([], $result['pass']);
  579. $result = $this->collection->parse('/articles/1');
  580. $this->assertEquals('Articles', $result['controller']);
  581. $this->assertEquals('view', $result['action']);
  582. $this->assertEquals([1], $result['pass']);
  583. $_SERVER['REQUEST_METHOD'] = 'POST';
  584. $result = $this->collection->parse('/articles');
  585. $this->assertEquals('Articles', $result['controller']);
  586. $this->assertEquals('add', $result['action']);
  587. $this->assertEquals([], $result['pass']);
  588. $_SERVER['REQUEST_METHOD'] = 'PUT';
  589. $result = $this->collection->parse('/articles/1');
  590. $this->assertEquals('Articles', $result['controller']);
  591. $this->assertEquals('edit', $result['action']);
  592. $this->assertEquals([1], $result['pass']);
  593. $_SERVER['REQUEST_METHOD'] = 'DELETE';
  594. $result = $this->collection->parse('/articles/1');
  595. $this->assertEquals('Articles', $result['controller']);
  596. $this->assertEquals('delete', $result['action']);
  597. $this->assertEquals([1], $result['pass']);
  598. }
  599. /**
  600. * Test the only option of RouteBuilder.
  601. *
  602. * @return void
  603. */
  604. public function testResourcesOnlyString()
  605. {
  606. $routes = new RouteBuilder($this->collection, '/');
  607. $routes->resources('Articles', ['only' => 'index']);
  608. $result = $this->collection->routes();
  609. $this->assertCount(1, $result);
  610. $this->assertEquals('/articles', $result[0]->template);
  611. }
  612. /**
  613. * Test the only option of RouteBuilder.
  614. *
  615. * @return void
  616. */
  617. public function testResourcesOnlyArray()
  618. {
  619. $routes = new RouteBuilder($this->collection, '/');
  620. $routes->resources('Articles', ['only' => ['index', 'delete']]);
  621. $result = $this->collection->routes();
  622. $this->assertCount(2, $result);
  623. $this->assertEquals('/articles', $result[0]->template);
  624. $this->assertEquals('index', $result[0]->defaults['action']);
  625. $this->assertEquals('GET', $result[0]->defaults['_method']);
  626. $this->assertEquals('/articles/:id', $result[1]->template);
  627. $this->assertEquals('delete', $result[1]->defaults['action']);
  628. $this->assertEquals('DELETE', $result[1]->defaults['_method']);
  629. }
  630. /**
  631. * Test the actions option of RouteBuilder.
  632. *
  633. * @return void
  634. */
  635. public function testResourcesActions()
  636. {
  637. $routes = new RouteBuilder($this->collection, '/');
  638. $routes->resources('Articles', [
  639. 'only' => ['index', 'delete'],
  640. 'actions' => ['index' => 'showList']
  641. ]);
  642. $result = $this->collection->routes();
  643. $this->assertCount(2, $result);
  644. $this->assertEquals('/articles', $result[0]->template);
  645. $this->assertEquals('showList', $result[0]->defaults['action']);
  646. $this->assertEquals('/articles/:id', $result[1]->template);
  647. $this->assertEquals('delete', $result[1]->defaults['action']);
  648. }
  649. /**
  650. * Test nesting resources
  651. *
  652. * @return void
  653. */
  654. public function testResourcesNested()
  655. {
  656. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  657. $routes->resources('Articles', function ($routes) {
  658. $this->assertEquals('/api/articles/', $routes->path());
  659. $this->assertEquals(['prefix' => 'api'], $routes->params());
  660. $routes->resources('Comments');
  661. $route = $this->collection->routes()[6];
  662. $this->assertEquals('/api/articles/:article_id/comments', $route->template);
  663. });
  664. }
  665. /**
  666. * Test connecting fallback routes.
  667. *
  668. * @return void
  669. */
  670. public function testFallbacks()
  671. {
  672. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  673. $routes->fallbacks();
  674. $all = $this->collection->routes();
  675. $this->assertEquals('/api/:controller', $all[0]->template);
  676. $this->assertEquals('/api/:controller/:action/*', $all[1]->template);
  677. $this->assertInstanceOf(Route::class, $all[0]);
  678. }
  679. /**
  680. * Test connecting fallback routes with specific route class
  681. *
  682. * @return void
  683. */
  684. public function testFallbacksWithClass()
  685. {
  686. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  687. $routes->fallbacks('InflectedRoute');
  688. $all = $this->collection->routes();
  689. $this->assertEquals('/api/:controller', $all[0]->template);
  690. $this->assertEquals('/api/:controller/:action/*', $all[1]->template);
  691. $this->assertInstanceOf(InflectedRoute::class, $all[0]);
  692. }
  693. /**
  694. * Test connecting fallback routes after setting default route class.
  695. *
  696. * @return void
  697. */
  698. public function testDefaultRouteClassFallbacks()
  699. {
  700. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  701. $routes->setRouteClass('TestApp\Routing\Route\DashedRoute');
  702. $routes->fallbacks();
  703. $all = $this->collection->routes();
  704. $this->assertInstanceOf('TestApp\Routing\Route\DashedRoute', $all[0]);
  705. }
  706. /**
  707. * Test adding a scope.
  708. *
  709. * @return void
  710. */
  711. public function testScope()
  712. {
  713. $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
  714. $routes->scope('/v1', ['version' => 1], function ($routes) {
  715. $this->assertEquals('/api/v1', $routes->path());
  716. $this->assertEquals(['prefix' => 'api', 'version' => 1], $routes->params());
  717. });
  718. }
  719. /**
  720. * Test that nested scopes inherit middleware.
  721. *
  722. * @return void
  723. */
  724. public function testScopeInheritMiddleware()
  725. {
  726. $routes = new RouteBuilder(
  727. $this->collection,
  728. '/api',
  729. ['prefix' => 'api'],
  730. ['middleware' => ['auth']]
  731. );
  732. $routes->scope('/v1', function ($routes) {
  733. $this->assertAttributeEquals(['auth'], 'middleware', $routes, 'Should inherit middleware');
  734. $this->assertEquals('/api/v1', $routes->path());
  735. $this->assertEquals(['prefix' => 'api'], $routes->params());
  736. });
  737. }
  738. /**
  739. * Test using name prefixes.
  740. *
  741. * @return void
  742. */
  743. public function testNamePrefixes()
  744. {
  745. $routes = new RouteBuilder($this->collection, '/api', [], ['namePrefix' => 'api:']);
  746. $routes->scope('/v1', ['version' => 1, '_namePrefix' => 'v1:'], function ($routes) {
  747. $this->assertEquals('api:v1:', $routes->namePrefix());
  748. $routes->connect('/ping', ['controller' => 'Pings'], ['_name' => 'ping']);
  749. $routes->namePrefix('web:');
  750. $routes->connect('/pong', ['controller' => 'Pongs'], ['_name' => 'pong']);
  751. });
  752. $all = $this->collection->named();
  753. $this->assertArrayHasKey('api:v1:ping', $all);
  754. $this->assertArrayHasKey('web:pong', $all);
  755. }
  756. /**
  757. * Test adding middleware to the collection.
  758. *
  759. * @return void
  760. */
  761. public function testRegisterMiddleware()
  762. {
  763. $func = function () {
  764. };
  765. $routes = new RouteBuilder($this->collection, '/api');
  766. $result = $routes->registerMiddleware('test', $func);
  767. $this->assertSame($result, $routes);
  768. $this->assertTrue($this->collection->hasMiddleware('test'));
  769. $this->assertTrue($this->collection->middlewareExists('test'));
  770. }
  771. /**
  772. * Test middleware group
  773. *
  774. * @return void
  775. */
  776. public function testMiddlewareGroup()
  777. {
  778. $func = function () {
  779. };
  780. $routes = new RouteBuilder($this->collection, '/api');
  781. $routes->registerMiddleware('test', $func);
  782. $routes->registerMiddleware('test_two', $func);
  783. $result = $routes->middlewareGroup('group', ['test', 'test_two']);
  784. $this->assertSame($result, $routes);
  785. $this->assertTrue($this->collection->hasMiddlewareGroup('group'));
  786. $this->assertTrue($this->collection->middlewareExists('group'));
  787. }
  788. /**
  789. * Test overlap between middleware name and group name
  790. *
  791. * @return void
  792. */
  793. public function testMiddlewareGroupOverlap()
  794. {
  795. $this->expectException(\RuntimeException::class);
  796. $this->expectExceptionMessage('Cannot add middleware group \'test\'. A middleware by this name has already been registered.');
  797. $func = function () {
  798. };
  799. $routes = new RouteBuilder($this->collection, '/api');
  800. $routes->registerMiddleware('test', $func);
  801. $result = $routes->middlewareGroup('test', ['test']);
  802. }
  803. /**
  804. * Test applying middleware to a scope when it doesn't exist
  805. *
  806. * @return void
  807. */
  808. public function testApplyMiddlewareInvalidName()
  809. {
  810. $this->expectException(\RuntimeException::class);
  811. $this->expectExceptionMessage('Cannot apply \'bad\' middleware or middleware group. Use registerMiddleware() to register middleware');
  812. $routes = new RouteBuilder($this->collection, '/api');
  813. $routes->applyMiddleware('bad');
  814. }
  815. /**
  816. * Test applying middleware to a scope
  817. *
  818. * @return void
  819. */
  820. public function testApplyMiddleware()
  821. {
  822. $func = function () {
  823. };
  824. $routes = new RouteBuilder($this->collection, '/api');
  825. $routes->registerMiddleware('test', $func)
  826. ->registerMiddleware('test2', $func);
  827. $result = $routes->applyMiddleware('test', 'test2');
  828. $this->assertSame($result, $routes);
  829. }
  830. /**
  831. * Test that applyMiddleware() merges with previous data.
  832. *
  833. * @return void
  834. */
  835. public function testApplyMiddlewareMerges()
  836. {
  837. $func = function () {
  838. };
  839. $routes = new RouteBuilder($this->collection, '/api');
  840. $routes->registerMiddleware('test', $func)
  841. ->registerMiddleware('test2', $func);
  842. $routes->applyMiddleware('test');
  843. $routes->applyMiddleware('test2');
  844. $this->assertAttributeEquals(['test', 'test2'], 'middleware', $routes);
  845. }
  846. /**
  847. * Test applying middleware results in middleware attached to the route.
  848. *
  849. * @return void
  850. */
  851. public function testApplyMiddlewareAttachToRoutes()
  852. {
  853. $func = function () {
  854. };
  855. $routes = new RouteBuilder($this->collection, '/api');
  856. $routes->registerMiddleware('test', $func)
  857. ->registerMiddleware('test2', $func);
  858. $routes->applyMiddleware('test', 'test2');
  859. $route = $routes->get('/docs', ['controller' => 'Docs']);
  860. $this->assertSame(['test', 'test2'], $route->getMiddleware());
  861. }
  862. /**
  863. * @return array
  864. */
  865. public static function httpMethodProvider()
  866. {
  867. return [
  868. ['GET'],
  869. ['POST'],
  870. ['PUT'],
  871. ['PATCH'],
  872. ['DELETE'],
  873. ['OPTIONS'],
  874. ['HEAD'],
  875. ];
  876. }
  877. /**
  878. * Test that the HTTP method helpers create the right kind of routes.
  879. *
  880. * @dataProvider httpMethodProvider
  881. * @return void
  882. */
  883. public function testHttpMethods($method)
  884. {
  885. $routes = new RouteBuilder($this->collection, '/', [], ['namePrefix' => 'app:']);
  886. $route = $routes->{strtolower($method)}(
  887. '/bookmarks/:id',
  888. ['controller' => 'Bookmarks', 'action' => 'view'],
  889. 'route-name'
  890. );
  891. $this->assertInstanceOf(Route::class, $route, 'Should return a route');
  892. $this->assertSame($method, $route->defaults['_method']);
  893. $this->assertSame('app:route-name', $route->options['_name']);
  894. $this->assertSame('/bookmarks/:id', $route->template);
  895. $this->assertEquals(
  896. ['plugin' => null, 'controller' => 'Bookmarks', 'action' => 'view', '_method' => $method],
  897. $route->defaults
  898. );
  899. }
  900. /**
  901. * Integration test for http method helpers and route fluent method
  902. *
  903. * @return void
  904. */
  905. public function testHttpMethodIntegration()
  906. {
  907. $routes = new RouteBuilder($this->collection, '/');
  908. $routes->scope('/', function ($routes) {
  909. $routes->get('/faq/:page', ['controller' => 'Pages', 'action' => 'faq'], 'faq')
  910. ->setPatterns(['page' => '[a-z0-9_]+'])
  911. ->setHost('docs.example.com');
  912. $routes->post('/articles/:id', ['controller' => 'Articles', 'action' => 'update'], 'article:update')
  913. ->setPatterns(['id' => '[0-9]+'])
  914. ->setPass(['id']);
  915. });
  916. $this->assertCount(2, $this->collection->routes());
  917. $this->assertEquals(['faq', 'article:update'], array_keys($this->collection->named()));
  918. $this->assertNotEmpty($this->collection->parse('/faq/things_you_know', 'GET'));
  919. $result = $this->collection->parse('/articles/123', 'POST');
  920. $this->assertEquals(['123'], $result['pass']);
  921. }
  922. /**
  923. * Test loading routes from a missing plugin
  924. *
  925. * @return void
  926. */
  927. public function testLoadPluginBadPlugin()
  928. {
  929. $this->expectException(\Cake\Core\Exception\MissingPluginException::class);
  930. $routes = new RouteBuilder($this->collection, '/');
  931. $routes->loadPlugin('Nope');
  932. }
  933. /**
  934. * Test loading routes from a missing file
  935. *
  936. * @return void
  937. */
  938. public function testLoadPluginBadFile()
  939. {
  940. $this->expectException(\InvalidArgumentException::class);
  941. $this->expectExceptionMessage('Cannot load routes for the plugin named TestPlugin.');
  942. Plugin::load('TestPlugin');
  943. $routes = new RouteBuilder($this->collection, '/');
  944. $routes->loadPlugin('TestPlugin', 'nope.php');
  945. }
  946. /**
  947. * Test loading routes with success
  948. *
  949. * @return void
  950. */
  951. public function testLoadPlugin()
  952. {
  953. Plugin::load('TestPlugin');
  954. $routes = new RouteBuilder($this->collection, '/');
  955. $routes->loadPlugin('TestPlugin');
  956. $this->assertCount(1, $this->collection->routes());
  957. $this->assertNotEmpty($this->collection->parse('/test_plugin', 'GET'));
  958. }
  959. /**
  960. * Test routeClass() still works.
  961. *
  962. * @return void
  963. */
  964. public function testRouteClassBackwardCompat()
  965. {
  966. $routes = new RouteBuilder($this->collection, '/l');
  967. $this->assertNull($routes->routeClass('TestApp\Routing\Route\DashedRoute'));
  968. $this->assertSame('TestApp\Routing\Route\DashedRoute', $routes->routeClass());
  969. $this->assertSame('TestApp\Routing\Route\DashedRoute', $routes->getRouteClass());
  970. }
  971. /**
  972. * Test extensions() still works.
  973. *
  974. * @return void
  975. */
  976. public function testExtensionsBackwardCompat()
  977. {
  978. $routes = new RouteBuilder($this->collection, '/l');
  979. $this->assertNull($routes->extensions(['html']));
  980. $this->assertSame(['html'], $routes->extensions());
  981. $this->assertSame(['html'], $routes->getExtensions());
  982. $this->assertNull($routes->extensions('json'));
  983. $this->assertSame(['json'], $routes->extensions());
  984. $this->assertSame(['json'], $routes->getExtensions());
  985. }
  986. }