RoutingMiddlewareTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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.3.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Routing\Middleware;
  16. use Cake\Cache\Cache;
  17. use Cake\Routing\Middleware\RoutingMiddleware;
  18. use Cake\Routing\RouteBuilder;
  19. use Cake\Routing\RouteCollection;
  20. use Cake\Routing\Router;
  21. use Cake\TestSuite\TestCase;
  22. use TestApp\Application;
  23. use TestApp\Middleware\DumbMiddleware;
  24. use Zend\Diactoros\Response;
  25. use Zend\Diactoros\ServerRequestFactory;
  26. /**
  27. * Test for RoutingMiddleware
  28. */
  29. class RoutingMiddlewareTest extends TestCase
  30. {
  31. protected $log = [];
  32. /**
  33. * Setup method
  34. *
  35. * @return void
  36. */
  37. public function setUp()
  38. {
  39. parent::setUp();
  40. Router::reload();
  41. Router::connect('/articles', ['controller' => 'Articles', 'action' => 'index']);
  42. $this->log = [];
  43. }
  44. /**
  45. * Test redirect responses from redirect routes
  46. *
  47. * @return void
  48. */
  49. public function testRedirectResponse()
  50. {
  51. Router::scope('/', function ($routes) {
  52. $routes->redirect('/testpath', '/pages');
  53. });
  54. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/testpath']);
  55. $request = $request->withAttribute('base', '/subdir');
  56. $response = new Response();
  57. $next = function ($req, $res) {
  58. };
  59. $middleware = new RoutingMiddleware();
  60. $response = $middleware($request, $response, $next);
  61. $this->assertEquals(301, $response->getStatusCode());
  62. $this->assertEquals('http://localhost/subdir/pages', $response->getHeaderLine('Location'));
  63. }
  64. /**
  65. * Test redirects with additional headers
  66. *
  67. * @return void
  68. */
  69. public function testRedirectResponseWithHeaders()
  70. {
  71. Router::scope('/', function ($routes) {
  72. $routes->redirect('/testpath', '/pages');
  73. });
  74. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/testpath']);
  75. $response = new Response('php://memory', 200, ['X-testing' => 'Yes']);
  76. $next = function ($req, $res) {
  77. };
  78. $middleware = new RoutingMiddleware();
  79. $response = $middleware($request, $response, $next);
  80. $this->assertEquals(301, $response->getStatusCode());
  81. $this->assertEquals('http://localhost/pages', $response->getHeaderLine('Location'));
  82. $this->assertEquals('Yes', $response->getHeaderLine('X-testing'));
  83. }
  84. /**
  85. * Test that Router sets parameters
  86. *
  87. * @return void
  88. */
  89. public function testRouterSetParams()
  90. {
  91. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  92. $response = new Response();
  93. $next = function ($req, $res) {
  94. $expected = [
  95. 'controller' => 'Articles',
  96. 'action' => 'index',
  97. 'plugin' => null,
  98. 'pass' => [],
  99. '_matchedRoute' => '/articles'
  100. ];
  101. $this->assertEquals($expected, $req->getAttribute('params'));
  102. };
  103. $middleware = new RoutingMiddleware();
  104. $middleware($request, $response, $next);
  105. }
  106. /**
  107. * Test routing middleware does wipe off existing params keys.
  108. *
  109. * @return void
  110. */
  111. public function testPreservingExistingParams()
  112. {
  113. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  114. $request = $request->withAttribute('params', ['_csrfToken' => 'i-am-groot']);
  115. $response = new Response();
  116. $next = function ($req, $res) {
  117. $expected = [
  118. 'controller' => 'Articles',
  119. 'action' => 'index',
  120. 'plugin' => null,
  121. 'pass' => [],
  122. '_matchedRoute' => '/articles',
  123. '_csrfToken' => 'i-am-groot'
  124. ];
  125. $this->assertEquals($expected, $req->getAttribute('params'));
  126. };
  127. $middleware = new RoutingMiddleware();
  128. $middleware($request, $response, $next);
  129. }
  130. /**
  131. * Test middleware invoking hook method
  132. *
  133. * @return void
  134. */
  135. public function testRoutesHookInvokedOnApp()
  136. {
  137. Router::reload();
  138. $this->assertFalse(Router::$initialized, 'Router precondition failed');
  139. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']);
  140. $response = new Response();
  141. $next = function ($req, $res) {
  142. $expected = [
  143. 'controller' => 'Articles',
  144. 'action' => 'index',
  145. 'plugin' => null,
  146. 'pass' => [],
  147. '_matchedRoute' => '/app/articles'
  148. ];
  149. $this->assertEquals($expected, $req->getAttribute('params'));
  150. $this->assertTrue(Router::$initialized, 'Router state should indicate routes loaded');
  151. $this->assertNotEmpty(Router::routes());
  152. $this->assertEquals('/app/articles', Router::routes()[0]->template);
  153. };
  154. $app = new Application(CONFIG);
  155. $middleware = new RoutingMiddleware($app);
  156. $middleware($request, $response, $next);
  157. }
  158. /**
  159. * Test that pluginRoutes hook is called
  160. *
  161. * @return void
  162. */
  163. public function testRoutesHookCallsPluginHook()
  164. {
  165. Router::reload();
  166. $this->assertFalse(Router::$initialized, 'Router precondition failed');
  167. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']);
  168. $response = new Response();
  169. $next = function ($req, $res) {
  170. return $res;
  171. };
  172. $app = $this->getMockBuilder(Application::class)
  173. ->setMethods(['pluginRoutes'])
  174. ->setConstructorArgs([CONFIG])
  175. ->getMock();
  176. $app->expects($this->once())
  177. ->method('pluginRoutes')
  178. ->with($this->isInstanceOf(RouteBuilder::class));
  179. $middleware = new RoutingMiddleware($app);
  180. $middleware($request, $response, $next);
  181. }
  182. /**
  183. * Test that routing is not applied if a controller exists already
  184. *
  185. * @return void
  186. */
  187. public function testRouterNoopOnController()
  188. {
  189. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  190. $request = $request->withAttribute('params', ['controller' => 'Articles']);
  191. $response = new Response();
  192. $next = function ($req, $res) {
  193. $this->assertEquals(['controller' => 'Articles'], $req->getAttribute('params'));
  194. };
  195. $middleware = new RoutingMiddleware();
  196. $middleware($request, $response, $next);
  197. }
  198. /**
  199. * Test missing routes not being caught.
  200. *
  201. */
  202. public function testMissingRouteNotCaught()
  203. {
  204. $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
  205. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/missing']);
  206. $response = new Response();
  207. $next = function ($req, $res) {
  208. };
  209. $middleware = new RoutingMiddleware();
  210. $middleware($request, $response, $next);
  211. }
  212. /**
  213. * Test route with _method being parsed correctly.
  214. *
  215. * @return void
  216. */
  217. public function testFakedRequestMethodParsed()
  218. {
  219. Router::connect('/articles-patch', [
  220. 'controller' => 'Articles',
  221. 'action' => 'index',
  222. '_method' => 'PATCH'
  223. ]);
  224. $request = ServerRequestFactory::fromGlobals(
  225. [
  226. 'REQUEST_METHOD' => 'POST',
  227. 'REQUEST_URI' => '/articles-patch'
  228. ],
  229. null,
  230. ['_method' => 'PATCH']
  231. );
  232. $response = new Response();
  233. $next = function ($req, $res) {
  234. $expected = [
  235. 'controller' => 'Articles',
  236. 'action' => 'index',
  237. '_method' => 'PATCH',
  238. 'plugin' => null,
  239. 'pass' => [],
  240. '_matchedRoute' => '/articles-patch'
  241. ];
  242. $this->assertEquals($expected, $req->getAttribute('params'));
  243. $this->assertEquals('PATCH', $req->getMethod());
  244. };
  245. $middleware = new RoutingMiddleware();
  246. $middleware($request, $response, $next);
  247. }
  248. /**
  249. * Test invoking simple scoped middleware
  250. *
  251. * @return void
  252. */
  253. public function testInvokeScopedMiddleware()
  254. {
  255. Router::scope('/api', function ($routes) {
  256. $routes->registerMiddleware('first', function ($req, $res, $next) {
  257. $this->log[] = 'first';
  258. return $next($req, $res);
  259. });
  260. $routes->registerMiddleware('second', function ($req, $res, $next) {
  261. $this->log[] = 'second';
  262. return $next($req, $res);
  263. });
  264. $routes->registerMiddleware('dumb', DumbMiddleware::class);
  265. // Connect middleware in reverse to test ordering.
  266. $routes->applyMiddleware('second', 'first', 'dumb');
  267. $routes->connect('/ping', ['controller' => 'Pings']);
  268. });
  269. $request = ServerRequestFactory::fromGlobals([
  270. 'REQUEST_METHOD' => 'GET',
  271. 'REQUEST_URI' => '/api/ping'
  272. ]);
  273. $response = new Response();
  274. $next = function ($req, $res) {
  275. $this->log[] = 'last';
  276. return $res;
  277. };
  278. $middleware = new RoutingMiddleware();
  279. $result = $middleware($request, $response, $next);
  280. $this->assertSame($response, $result, 'Should return result');
  281. $this->assertSame(['second', 'first', 'last'], $this->log);
  282. }
  283. /**
  284. * Test control flow in scoped middleware.
  285. *
  286. * Scoped middleware should be able to generate a response
  287. * and abort lower layers.
  288. *
  289. * @return void
  290. */
  291. public function testInvokeScopedMiddlewareReturnResponse()
  292. {
  293. Router::scope('/', function ($routes) {
  294. $routes->registerMiddleware('first', function ($req, $res, $next) {
  295. $this->log[] = 'first';
  296. return $next($req, $res);
  297. });
  298. $routes->registerMiddleware('second', function ($req, $res, $next) {
  299. $this->log[] = 'second';
  300. return $res;
  301. });
  302. $routes->applyMiddleware('first');
  303. $routes->connect('/', ['controller' => 'Home']);
  304. $routes->scope('/api', function ($routes) {
  305. $routes->applyMiddleware('second');
  306. $routes->connect('/articles', ['controller' => 'Articles']);
  307. });
  308. });
  309. $request = ServerRequestFactory::fromGlobals([
  310. 'REQUEST_METHOD' => 'GET',
  311. 'REQUEST_URI' => '/api/articles'
  312. ]);
  313. $response = new Response();
  314. $next = function ($req, $res) {
  315. $this->fail('Should not be invoked as first should be ignored.');
  316. };
  317. $middleware = new RoutingMiddleware();
  318. $result = $middleware($request, $response, $next);
  319. $this->assertSame($response, $result, 'Should return result');
  320. $this->assertSame(['first', 'second'], $this->log);
  321. }
  322. /**
  323. * Test control flow in scoped middleware.
  324. *
  325. * @return void
  326. */
  327. public function testInvokeScopedMiddlewareReturnResponseMainScope()
  328. {
  329. Router::scope('/', function ($routes) {
  330. $routes->registerMiddleware('first', function ($req, $res, $next) {
  331. $this->log[] = 'first';
  332. return $res;
  333. });
  334. $routes->registerMiddleware('second', function ($req, $res, $next) {
  335. $this->log[] = 'second';
  336. return $next($req, $res);
  337. });
  338. $routes->applyMiddleware('first');
  339. $routes->connect('/', ['controller' => 'Home']);
  340. $routes->scope('/api', function ($routes) {
  341. $routes->applyMiddleware('second');
  342. $routes->connect('/articles', ['controller' => 'Articles']);
  343. });
  344. });
  345. $request = ServerRequestFactory::fromGlobals([
  346. 'REQUEST_METHOD' => 'GET',
  347. 'REQUEST_URI' => '/'
  348. ]);
  349. $response = new Response();
  350. $next = function ($req, $res) {
  351. $this->fail('Should not be invoked as second should be ignored.');
  352. };
  353. $middleware = new RoutingMiddleware();
  354. $result = $middleware($request, $response, $next);
  355. $this->assertSame($response, $result, 'Should return result');
  356. $this->assertSame(['first'], $this->log);
  357. }
  358. /**
  359. * Test invoking middleware & scope separation
  360. *
  361. * Re-opening a scope should not inherit middleware declared
  362. * in the first context.
  363. *
  364. * @dataProvider scopedMiddlewareUrlProvider
  365. * @return void
  366. */
  367. public function testInvokeScopedMiddlewareIsolatedScopes($url, $expected)
  368. {
  369. Router::scope('/', function ($routes) {
  370. $routes->registerMiddleware('first', function ($req, $res, $next) {
  371. $this->log[] = 'first';
  372. return $next($req, $res);
  373. });
  374. $routes->registerMiddleware('second', function ($req, $res, $next) {
  375. $this->log[] = 'second';
  376. return $next($req, $res);
  377. });
  378. $routes->scope('/api', function ($routes) {
  379. $routes->applyMiddleware('first');
  380. $routes->connect('/ping', ['controller' => 'Pings']);
  381. });
  382. $routes->scope('/api', function ($routes) {
  383. $routes->applyMiddleware('second');
  384. $routes->connect('/version', ['controller' => 'Version']);
  385. });
  386. });
  387. $request = ServerRequestFactory::fromGlobals([
  388. 'REQUEST_METHOD' => 'GET',
  389. 'REQUEST_URI' => $url
  390. ]);
  391. $response = new Response();
  392. $next = function ($req, $res) {
  393. $this->log[] = 'last';
  394. return $res;
  395. };
  396. $middleware = new RoutingMiddleware();
  397. $result = $middleware($request, $response, $next);
  398. $this->assertSame($response, $result, 'Should return result');
  399. $this->assertSame($expected, $this->log);
  400. }
  401. /**
  402. * Provider for scope isolation test.
  403. *
  404. * @return array
  405. */
  406. public function scopedMiddlewareUrlProvider()
  407. {
  408. return [
  409. ['/api/ping', ['first', 'last']],
  410. ['/api/version', ['second', 'last']],
  411. ];
  412. }
  413. /**
  414. * Test we store route collection in cache.
  415. *
  416. * @return void
  417. */
  418. public function testCacheRoutes()
  419. {
  420. $cacheConfigName = '_cake_router_';
  421. Cache::setConfig($cacheConfigName, [
  422. 'engine' => 'File',
  423. 'path' => CACHE,
  424. ]);
  425. Router::$initialized = false;
  426. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  427. $response = new Response();
  428. $next = function ($req, $res) use ($cacheConfigName) {
  429. $routeCollection = Cache::read('routeCollection', $cacheConfigName);
  430. $this->assertInstanceOf(RouteCollection::class, $routeCollection);
  431. return $res;
  432. };
  433. $app = new Application(CONFIG);
  434. $middleware = new RoutingMiddleware($app, $cacheConfigName);
  435. $middleware($request, $response, $next);
  436. Cache::clear(false, $cacheConfigName);
  437. Cache::drop($cacheConfigName);
  438. }
  439. /**
  440. * Test we don't cache routes if cache is disabled.
  441. *
  442. * @return void
  443. */
  444. public function testCacheNotUsedIfCacheDisabled()
  445. {
  446. $cacheConfigName = '_cake_router_';
  447. Cache::disable();
  448. Cache::setConfig($cacheConfigName, [
  449. 'engine' => 'File',
  450. 'path' => CACHE,
  451. ]);
  452. Router::$initialized = false;
  453. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  454. $response = new Response();
  455. $next = function ($req, $res) use ($cacheConfigName) {
  456. $routeCollection = Cache::read('routeCollection', $cacheConfigName);
  457. $this->assertFalse($routeCollection);
  458. return $res;
  459. };
  460. $app = new Application(CONFIG);
  461. $middleware = new RoutingMiddleware($app, $cacheConfigName);
  462. $middleware($request, $response, $next);
  463. Cache::clear(false, $cacheConfigName);
  464. Cache::drop($cacheConfigName);
  465. Cache::enable();
  466. }
  467. /**
  468. * Test cache name is used
  469. *
  470. * @return void
  471. */
  472. public function testCacheConfigNotFound()
  473. {
  474. $this->expectException(\InvalidArgumentException::class);
  475. $this->expectExceptionMessage('The "notfound" cache configuration does not exist');
  476. Cache::setConfig('_cake_router_', [
  477. 'engine' => 'File',
  478. 'path' => CACHE,
  479. ]);
  480. Router::$initialized = false;
  481. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  482. $response = new Response();
  483. $next = function ($req, $res) {
  484. return $res;
  485. };
  486. $app = new Application(CONFIG);
  487. $middleware = new RoutingMiddleware($app, 'notfound');
  488. $middleware($request, $response, $next);
  489. Cache::drop('_cake_router_');
  490. }
  491. }