RouteCollectionTest.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Routing;
  16. use Cake\Http\ServerRequest;
  17. use Cake\Routing\Exception\MissingRouteException;
  18. use Cake\Routing\RouteBuilder;
  19. use Cake\Routing\RouteCollection;
  20. use Cake\Routing\Route\Route;
  21. use Cake\TestSuite\TestCase;
  22. use \stdClass;
  23. class RouteCollectionTest extends TestCase
  24. {
  25. /**
  26. * Setup method
  27. *
  28. * @return void
  29. */
  30. public function setUp()
  31. {
  32. parent::setUp();
  33. $this->collection = new RouteCollection();
  34. }
  35. /**
  36. * Test parse() throws an error on unknown routes.
  37. *
  38. * @expectedException \Cake\Routing\Exception\MissingRouteException
  39. * @expectedExceptionMessage A route matching "/" could not be found
  40. */
  41. public function testParseMissingRoute()
  42. {
  43. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  44. $routes->connect('/', ['controller' => 'Articles']);
  45. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
  46. $result = $this->collection->parse('/');
  47. $this->assertEquals([], $result, 'Should not match, missing /b');
  48. }
  49. /**
  50. * Test parse() throws an error on known routes called with unknown methods.
  51. *
  52. * @expectedException \Cake\Routing\Exception\MissingRouteException
  53. * @expectedExceptionMessage A "POST" route matching "/b" could not be found
  54. */
  55. public function testParseMissingRouteMethod()
  56. {
  57. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  58. $routes->connect('/', ['controller' => 'Articles', '_method' => ['GET']]);
  59. $result = $this->collection->parse('/b', 'GET');
  60. $this->assertNotEmpty($result, 'Route should be found');
  61. $result = $this->collection->parse('/b', 'POST');
  62. $this->assertEquals([], $result, 'Should not match with missing method');
  63. }
  64. /**
  65. * Test parsing routes.
  66. *
  67. * @return void
  68. */
  69. public function testParse()
  70. {
  71. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  72. $routes->connect('/', ['controller' => 'Articles']);
  73. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
  74. $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search']);
  75. $result = $this->collection->parse('/b/');
  76. $expected = [
  77. 'controller' => 'Articles',
  78. 'action' => 'index',
  79. 'pass' => [],
  80. 'plugin' => null,
  81. 'key' => 'value',
  82. '_matchedRoute' => '/b',
  83. ];
  84. $this->assertEquals($expected, $result);
  85. $result = $this->collection->parse('/b/the-thing?one=two');
  86. $expected = [
  87. 'controller' => 'Articles',
  88. 'action' => 'view',
  89. 'id' => 'the-thing',
  90. 'pass' => [],
  91. 'plugin' => null,
  92. 'key' => 'value',
  93. '?' => ['one' => 'two'],
  94. '_matchedRoute' => '/b/:id',
  95. ];
  96. $this->assertEquals($expected, $result);
  97. $result = $this->collection->parse('/b/media/search');
  98. $expected = [
  99. 'key' => 'value',
  100. 'pass' => [],
  101. 'plugin' => null,
  102. 'controller' => 'Media',
  103. 'action' => 'search',
  104. '_matchedRoute' => '/b/media/search/*',
  105. ];
  106. $this->assertEquals($expected, $result);
  107. $result = $this->collection->parse('/b/media/search/thing');
  108. $expected = [
  109. 'key' => 'value',
  110. 'pass' => ['thing'],
  111. 'plugin' => null,
  112. 'controller' => 'Media',
  113. 'action' => 'search',
  114. '_matchedRoute' => '/b/media/search/*',
  115. ];
  116. $this->assertEquals($expected, $result);
  117. }
  118. /**
  119. * Test that parse decodes URL data before matching.
  120. * This is important for multibyte URLs that pass through URL rewriting.
  121. *
  122. * @return void
  123. */
  124. public function testParseEncodedBytesInFixedSegment()
  125. {
  126. $routes = new RouteBuilder($this->collection, '/');
  127. $routes->connect('/ден/:day-:month', ['controller' => 'Events', 'action' => 'index']);
  128. $url = '/%D0%B4%D0%B5%D0%BD/15-%D0%BE%D0%BA%D1%82%D0%BE%D0%BC%D0%B2%D1%80%D0%B8?test=foo';
  129. $result = $this->collection->parse($url);
  130. $expected = [
  131. 'pass' => [],
  132. 'plugin' => null,
  133. 'controller' => 'Events',
  134. 'action' => 'index',
  135. 'day' => '15',
  136. 'month' => 'октомври',
  137. '?' => ['test' => 'foo'],
  138. '_matchedRoute' => '/ден/:day-:month',
  139. ];
  140. $this->assertEquals($expected, $result);
  141. $request = new ServerRequest(['url' => $url]);
  142. $result = $this->collection->parseRequest($request);
  143. $this->assertEquals($expected, $result);
  144. }
  145. /**
  146. * Test that parsing checks all the related path scopes.
  147. *
  148. * @return void
  149. */
  150. public function testParseFallback()
  151. {
  152. $routes = new RouteBuilder($this->collection, '/', []);
  153. $routes->resources('Articles');
  154. $routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);
  155. $routes->connect('/:controller/:action', [], ['routeClass' => 'InflectedRoute']);
  156. $result = $this->collection->parse('/articles/add');
  157. $expected = [
  158. 'controller' => 'Articles',
  159. 'action' => 'add',
  160. 'plugin' => null,
  161. 'pass' => [],
  162. '_matchedRoute' => '/:controller/:action',
  163. ];
  164. $this->assertEquals($expected, $result);
  165. }
  166. /**
  167. * Test parseRequest() throws an error on unknown routes.
  168. *
  169. * @expectedException \Cake\Routing\Exception\MissingRouteException
  170. * @expectedExceptionMessage A route matching "/" could not be found
  171. */
  172. public function testParseRequestMissingRoute()
  173. {
  174. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  175. $routes->connect('/', ['controller' => 'Articles']);
  176. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
  177. $request = new ServerRequest(['url' => '/']);
  178. $result = $this->collection->parseRequest($request);
  179. $this->assertEquals([], $result, 'Should not match, missing /b');
  180. }
  181. /**
  182. * Test parseRequest() checks host conditions
  183. *
  184. * @return void
  185. */
  186. public function testParseRequestCheckHostCondition()
  187. {
  188. $routes = new RouteBuilder($this->collection, '/');
  189. $routes->connect(
  190. '/fallback',
  191. ['controller' => 'Articles', 'action' => 'index'],
  192. ['_host' => '*.example.com']
  193. );
  194. $request = new ServerRequest([
  195. 'environment' => [
  196. 'HTTP_HOST' => 'a.example.com',
  197. 'PATH_INFO' => '/fallback'
  198. ]
  199. ]);
  200. $result = $this->collection->parseRequest($request);
  201. $expected = [
  202. 'controller' => 'Articles',
  203. 'action' => 'index',
  204. 'pass' => [],
  205. 'plugin' => null,
  206. '_matchedRoute' => '/fallback'
  207. ];
  208. $this->assertEquals($expected, $result, 'Should match, domain is correct');
  209. $request = new ServerRequest([
  210. 'environment' => [
  211. 'HTTP_HOST' => 'foo.bar.example.com',
  212. 'PATH_INFO' => '/fallback'
  213. ]
  214. ]);
  215. $result = $this->collection->parseRequest($request);
  216. $this->assertEquals($expected, $result, 'Should match, domain is a matching subdomain');
  217. $request = new ServerRequest([
  218. 'environment' => [
  219. 'HTTP_HOST' => 'example.test.com',
  220. 'PATH_INFO' => '/fallback'
  221. ]
  222. ]);
  223. try {
  224. $this->collection->parseRequest($request);
  225. $this->fail('No exception raised');
  226. } catch (MissingRouteException $e) {
  227. $this->assertContains('/fallback', $e->getMessage());
  228. }
  229. }
  230. /**
  231. * Get a list of hostnames
  232. *
  233. * @return array
  234. */
  235. public static function hostProvider()
  236. {
  237. return [
  238. ['wrong.example'],
  239. ['example.com'],
  240. ['aexample.com'],
  241. ];
  242. }
  243. /**
  244. * Test parseRequest() checks host conditions
  245. *
  246. * @dataProvider hostProvider
  247. * @expectedException \Cake\Routing\Exception\MissingRouteException
  248. * @expectedExceptionMessage A route matching "/fallback" could not be found
  249. */
  250. public function testParseRequestCheckHostConditionFail($host)
  251. {
  252. $routes = new RouteBuilder($this->collection, '/');
  253. $routes->connect(
  254. '/fallback',
  255. ['controller' => 'Articles', 'action' => 'index'],
  256. ['_host' => '*.example.com']
  257. );
  258. $request = new ServerRequest([
  259. 'environment' => [
  260. 'HTTP_HOST' => $host,
  261. 'PATH_INFO' => '/fallback'
  262. ]
  263. ]);
  264. $this->collection->parseRequest($request);
  265. }
  266. /**
  267. * Test parsing routes.
  268. *
  269. * @return void
  270. */
  271. public function testParseRequest()
  272. {
  273. $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
  274. $routes->connect('/', ['controller' => 'Articles']);
  275. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
  276. $routes->connect('/media/search/*', ['controller' => 'Media', 'action' => 'search']);
  277. $request = new ServerRequest(['url' => '/b/']);
  278. $result = $this->collection->parseRequest($request);
  279. $expected = [
  280. 'controller' => 'Articles',
  281. 'action' => 'index',
  282. 'pass' => [],
  283. 'plugin' => null,
  284. 'key' => 'value',
  285. '_matchedRoute' => '/b',
  286. ];
  287. $this->assertEquals($expected, $result);
  288. $request = new ServerRequest(['url' => '/b/media/search']);
  289. $result = $this->collection->parseRequest($request);
  290. $expected = [
  291. 'key' => 'value',
  292. 'pass' => [],
  293. 'plugin' => null,
  294. 'controller' => 'Media',
  295. 'action' => 'search',
  296. '_matchedRoute' => '/b/media/search/*',
  297. ];
  298. $this->assertEquals($expected, $result);
  299. $request = new ServerRequest(['url' => '/b/media/search/thing']);
  300. $result = $this->collection->parseRequest($request);
  301. $expected = [
  302. 'key' => 'value',
  303. 'pass' => ['thing'],
  304. 'plugin' => null,
  305. 'controller' => 'Media',
  306. 'action' => 'search',
  307. '_matchedRoute' => '/b/media/search/*',
  308. ];
  309. $this->assertEquals($expected, $result);
  310. $request = new ServerRequest(['url' => '/b/the-thing?one=two']);
  311. $result = $this->collection->parseRequest($request);
  312. $expected = [
  313. 'controller' => 'Articles',
  314. 'action' => 'view',
  315. 'id' => 'the-thing',
  316. 'pass' => [],
  317. 'plugin' => null,
  318. 'key' => 'value',
  319. '?' => ['one' => 'two'],
  320. '_matchedRoute' => '/b/:id',
  321. ];
  322. $this->assertEquals($expected, $result);
  323. }
  324. /**
  325. * Test parsing routes that match non-ascii urls
  326. *
  327. * @return void
  328. */
  329. public function testParseRequestUnicode()
  330. {
  331. $routes = new RouteBuilder($this->collection, '/b', []);
  332. $routes->connect('/alta/confirmación', ['controller' => 'Media', 'action' => 'confirm']);
  333. $request = new ServerRequest(['url' => '/b/alta/confirmaci%C3%B3n']);
  334. $result = $this->collection->parseRequest($request);
  335. $expected = [
  336. 'controller' => 'Media',
  337. 'action' => 'confirm',
  338. 'pass' => [],
  339. 'plugin' => null,
  340. '_matchedRoute' => '/b/alta/confirmación',
  341. ];
  342. $this->assertEquals($expected, $result);
  343. $request = new ServerRequest(['url' => '/b/alta/confirmación']);
  344. $result = $this->collection->parseRequest($request);
  345. $this->assertEquals($expected, $result);
  346. }
  347. /**
  348. * Test match() throws an error on unknown routes.
  349. *
  350. * @expectedException \Cake\Routing\Exception\MissingRouteException
  351. * @expectedExceptionMessage A route matching "array (
  352. */
  353. public function testMatchError()
  354. {
  355. $context = [
  356. '_base' => '/',
  357. '_scheme' => 'http',
  358. '_host' => 'example.org',
  359. ];
  360. $routes = new RouteBuilder($this->collection, '/b');
  361. $routes->connect('/', ['controller' => 'Articles']);
  362. $this->collection->match(['plugin' => null, 'controller' => 'Articles', 'action' => 'add'], $context);
  363. }
  364. /**
  365. * Test matching routes.
  366. *
  367. * @return void
  368. */
  369. public function testMatch()
  370. {
  371. $context = [
  372. '_base' => '/',
  373. '_scheme' => 'http',
  374. '_host' => 'example.org',
  375. ];
  376. $routes = new RouteBuilder($this->collection, '/b');
  377. $routes->connect('/', ['controller' => 'Articles']);
  378. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
  379. $result = $this->collection->match(['plugin' => null, 'controller' => 'Articles', 'action' => 'index'], $context);
  380. $this->assertEquals('b', $result);
  381. $result = $this->collection->match(
  382. ['id' => 'thing', 'plugin' => null, 'controller' => 'Articles', 'action' => 'view'],
  383. $context
  384. );
  385. $this->assertEquals('b/thing', $result);
  386. }
  387. /**
  388. * Test matching routes with names
  389. *
  390. * @return void
  391. */
  392. public function testMatchNamed()
  393. {
  394. $context = [
  395. '_base' => '/',
  396. '_scheme' => 'http',
  397. '_host' => 'example.org',
  398. ];
  399. $routes = new RouteBuilder($this->collection, '/b');
  400. $routes->connect('/', ['controller' => 'Articles']);
  401. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view'], ['_name' => 'article:view']);
  402. $result = $this->collection->match(['_name' => 'article:view', 'id' => '2'], $context);
  403. $this->assertEquals('/b/2', $result);
  404. $result = $this->collection->match(['plugin' => null, 'controller' => 'Articles', 'action' => 'view', 'id' => '2'], $context);
  405. $this->assertEquals('b/2', $result);
  406. }
  407. /**
  408. * Test match() throws an error on named routes that fail to match
  409. *
  410. * @expectedException \Cake\Routing\Exception\MissingRouteException
  411. * @expectedExceptionMessage A named route was found for "fail", but matching failed
  412. */
  413. public function testMatchNamedError()
  414. {
  415. $context = [
  416. '_base' => '/',
  417. '_scheme' => 'http',
  418. '_host' => 'example.org',
  419. ];
  420. $routes = new RouteBuilder($this->collection, '/b');
  421. $routes->connect('/:lang/articles', ['controller' => 'Articles'], ['_name' => 'fail']);
  422. $this->collection->match(['_name' => 'fail'], $context);
  423. }
  424. /**
  425. * Test matching routes with names and failing
  426. *
  427. * @expectedException \Cake\Routing\Exception\MissingRouteException
  428. * @return void
  429. */
  430. public function testMatchNamedMissingError()
  431. {
  432. $context = [
  433. '_base' => '/',
  434. '_scheme' => 'http',
  435. '_host' => 'example.org',
  436. ];
  437. $routes = new RouteBuilder($this->collection, '/b');
  438. $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view'], ['_name' => 'article:view']);
  439. $this->collection->match(['_name' => 'derp'], $context);
  440. }
  441. /**
  442. * Test matching plugin routes.
  443. *
  444. * @return void
  445. */
  446. public function testMatchPlugin()
  447. {
  448. $context = [
  449. '_base' => '/',
  450. '_scheme' => 'http',
  451. '_host' => 'example.org',
  452. ];
  453. $routes = new RouteBuilder($this->collection, '/contacts', ['plugin' => 'Contacts']);
  454. $routes->connect('/', ['controller' => 'Contacts']);
  455. $result = $this->collection->match(['plugin' => 'Contacts', 'controller' => 'Contacts', 'action' => 'index'], $context);
  456. $this->assertEquals('contacts', $result);
  457. }
  458. /**
  459. * Test that prefixes increase the specificity of a route match.
  460. *
  461. * Connect the admin route after the non prefixed version, this means
  462. * the non-prefix route would have a more specific name (users:index)
  463. *
  464. * @return void
  465. */
  466. public function testMatchPrefixSpecificity()
  467. {
  468. $context = [
  469. '_base' => '/',
  470. '_scheme' => 'http',
  471. '_host' => 'example.org',
  472. ];
  473. $routes = new RouteBuilder($this->collection, '/');
  474. $routes->connect('/:action/*', ['controller' => 'Users']);
  475. $routes->connect('/admin/:controller', ['prefix' => 'admin', 'action' => 'index']);
  476. $url = [
  477. 'plugin' => null,
  478. 'prefix' => 'admin',
  479. 'controller' => 'Users',
  480. 'action' => 'index'
  481. ];
  482. $result = $this->collection->match($url, $context);
  483. $this->assertEquals('admin/Users', $result);
  484. $url = [
  485. 'plugin' => null,
  486. 'controller' => 'Users',
  487. 'action' => 'index'
  488. ];
  489. $result = $this->collection->match($url, $context);
  490. $this->assertEquals('index', $result);
  491. }
  492. /**
  493. * Test getting named routes.
  494. *
  495. * @return void
  496. */
  497. public function testNamed()
  498. {
  499. $routes = new RouteBuilder($this->collection, '/l');
  500. $routes->connect('/:controller', ['action' => 'index'], ['_name' => 'cntrl']);
  501. $routes->connect('/:controller/:action/*');
  502. $all = $this->collection->named();
  503. $this->assertCount(1, $all);
  504. $this->assertInstanceOf('Cake\Routing\Route\Route', $all['cntrl']);
  505. $this->assertEquals('/l/:controller', $all['cntrl']->template);
  506. }
  507. /**
  508. * Test the add() and routes() method.
  509. *
  510. * @return void
  511. */
  512. public function testAddingRoutes()
  513. {
  514. $one = new Route('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
  515. $two = new Route('/', ['controller' => 'Dashboards', 'action' => 'display']);
  516. $this->collection->add($one);
  517. $this->collection->add($two);
  518. $routes = $this->collection->routes();
  519. $this->assertCount(2, $routes);
  520. $this->assertSame($one, $routes[0]);
  521. $this->assertSame($two, $routes[1]);
  522. }
  523. /**
  524. * Test the add() with some _name.
  525. *
  526. * @expectedException \Cake\Routing\Exception\DuplicateNamedRouteException
  527. *
  528. * @return void
  529. */
  530. public function testAddingDuplicateNamedRoutes()
  531. {
  532. $one = new Route('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
  533. $two = new Route('/', ['controller' => 'Dashboards', 'action' => 'display']);
  534. $this->collection->add($one, ['_name' => 'test']);
  535. $this->collection->add($two, ['_name' => 'test']);
  536. }
  537. /**
  538. * Test get/set combined method.
  539. *
  540. * @return void
  541. * @deprecated 3.5.0
  542. */
  543. public function testExtensions()
  544. {
  545. $this->assertEquals([], $this->collection->extensions());
  546. $this->collection->extensions('json');
  547. $this->assertEquals(['json'], $this->collection->extensions());
  548. $this->collection->extensions(['rss', 'xml']);
  549. $this->assertEquals(['json', 'rss', 'xml'], $this->collection->extensions());
  550. $this->collection->extensions(['csv'], false);
  551. $this->assertEquals(['csv'], $this->collection->extensions());
  552. }
  553. /**
  554. * Test basic setExtension and its getter.
  555. *
  556. * @return void
  557. */
  558. public function testSetExtensions()
  559. {
  560. $this->assertEquals([], $this->collection->getExtensions());
  561. $this->collection->setExtensions(['json']);
  562. $this->assertEquals(['json'], $this->collection->getExtensions());
  563. $this->collection->setExtensions(['rss', 'xml']);
  564. $this->assertEquals(['json', 'rss', 'xml'], $this->collection->getExtensions());
  565. $this->collection->setExtensions(['csv'], false);
  566. $this->assertEquals(['csv'], $this->collection->getExtensions());
  567. }
  568. /**
  569. * String methods are not acceptable.
  570. *
  571. * @expectedException \RuntimeException
  572. * @expectedExceptionMessage The 'bad' middleware is not a callable object.
  573. * @return void
  574. */
  575. public function testRegisterMiddlewareNoCallableString()
  576. {
  577. $this->collection->registerMiddleware('bad', 'strlen');
  578. }
  579. /**
  580. * Test adding middleware to the collection.
  581. *
  582. * @return void
  583. */
  584. public function testRegisterMiddleware()
  585. {
  586. $result = $this->collection->registerMiddleware('closure', function () {
  587. });
  588. $this->assertSame($result, $this->collection);
  589. $mock = $this->getMockBuilder('\stdClass')
  590. ->setMethods(['__invoke'])
  591. ->getMock();
  592. $result = $this->collection->registerMiddleware('callable', $mock);
  593. $this->assertSame($result, $this->collection);
  594. $this->assertTrue($this->collection->hasMiddleware('closure'));
  595. $this->assertTrue($this->collection->hasMiddleware('callable'));
  596. }
  597. /**
  598. * Test adding middleware with a placeholder in the path.
  599. *
  600. * @return void
  601. */
  602. public function testApplyMiddlewareBasic()
  603. {
  604. $mock = $this->getMockBuilder('\stdClass')
  605. ->setMethods(['__invoke'])
  606. ->getMock();
  607. $this->collection->registerMiddleware('callable', $mock);
  608. $this->collection->registerMiddleware('callback_two', $mock);
  609. $result = $this->collection->applyMiddleware('/api', ['callable', 'callback_two']);
  610. $this->assertSame($result, $this->collection);
  611. }
  612. /**
  613. * Test adding middleware with a placeholder in the path.
  614. *
  615. * @return void
  616. */
  617. public function testGetMatchingMiddlewareBasic()
  618. {
  619. $mock = $this->getMockBuilder('\stdClass')
  620. ->setMethods(['__invoke'])
  621. ->getMock();
  622. $this->collection->registerMiddleware('callable', $mock);
  623. $this->collection->registerMiddleware('callback_two', $mock);
  624. $result = $this->collection->applyMiddleware('/api', ['callable']);
  625. $middleware = $this->collection->getMatchingMiddleware('/api/v1/articles');
  626. $this->assertCount(1, $middleware);
  627. $this->assertSame($middleware[0], $mock);
  628. }
  629. /**
  630. * Test enabling and matching
  631. *
  632. * @return void
  633. */
  634. public function testGetMatchingMiddlewareMultiplePaths()
  635. {
  636. $mock = $this->getMockBuilder('\stdClass')
  637. ->setMethods(['__invoke'])
  638. ->getMock();
  639. $mockTwo = $this->getMockBuilder('\stdClass')
  640. ->setMethods(['__invoke'])
  641. ->getMock();
  642. $this->collection->registerMiddleware('callable', $mock);
  643. $this->collection->registerMiddleware('callback_two', $mockTwo);
  644. $this->collection->applyMiddleware('/api', ['callable']);
  645. $this->collection->applyMiddleware('/api/v1/articles', ['callback_two']);
  646. $middleware = $this->collection->getMatchingMiddleware('/articles');
  647. $this->assertCount(0, $middleware);
  648. $middleware = $this->collection->getMatchingMiddleware('/api/v1/articles/1');
  649. $this->assertCount(2, $middleware);
  650. $this->assertEquals([$mock, $mockTwo], $middleware, 'Both middleware match');
  651. $middleware = $this->collection->getMatchingMiddleware('/api/v1/comments');
  652. $this->assertCount(1, $middleware);
  653. $this->assertEquals([$mock], $middleware, 'Should not match /articles middleware');
  654. }
  655. /**
  656. * Test enabling and matching
  657. *
  658. * @return void
  659. */
  660. public function testGetMatchingMiddlewareDeduplicate()
  661. {
  662. $mock = $this->getMockBuilder('\stdClass')
  663. ->setMethods(['__invoke'])
  664. ->getMock();
  665. $mockTwo = $this->getMockBuilder('\stdClass')
  666. ->setMethods(['__invoke'])
  667. ->getMock();
  668. $this->collection->registerMiddleware('callable', $mock);
  669. $this->collection->registerMiddleware('callback_two', $mockTwo);
  670. $this->collection->applyMiddleware('/api', ['callable']);
  671. $this->collection->applyMiddleware('/api/v1/articles', ['callback_two', 'callable']);
  672. $middleware = $this->collection->getMatchingMiddleware('/api/v1/articles/1');
  673. $this->assertCount(2, $middleware);
  674. $this->assertEquals([$mock, $mockTwo], $middleware, 'Both middleware match');
  675. }
  676. /**
  677. * Test adding middleware with a placeholder in the path.
  678. *
  679. * @return void
  680. */
  681. public function testApplyMiddlewareWithPlaceholder()
  682. {
  683. $mock = $this->getMockBuilder('\stdClass')
  684. ->setMethods(['__invoke'])
  685. ->getMock();
  686. $this->collection->registerMiddleware('callable', $mock);
  687. $this->collection->applyMiddleware('/api-:version/articles/:article_id/comments', ['callable']);
  688. $middleware = $this->collection->getMatchingMiddleware('/api-1/articles/comments');
  689. $this->assertEmpty($middleware);
  690. $middleware = $this->collection->getMatchingMiddleware('/api-1/articles/yay/comments');
  691. $this->assertEquals([$mock], $middleware);
  692. $middleware = $this->collection->getMatchingMiddleware('/api-1/articles/123/comments');
  693. $this->assertEquals([$mock], $middleware);
  694. $middleware = $this->collection->getMatchingMiddleware('/api-abc123/articles/abc-123/comments/99');
  695. $this->assertEquals([$mock], $middleware);
  696. }
  697. /**
  698. * Test applying middleware to a scope when it doesn't exist
  699. *
  700. * @expectedException \RuntimeException
  701. * @expectedExceptionMessage Cannot apply 'bad' middleware to path '/api'. It has not been registered.
  702. * @return void
  703. */
  704. public function testApplyMiddlewareUnregistered()
  705. {
  706. $mock = $this->getMockBuilder('\stdClass')
  707. ->setMethods(['__invoke'])
  708. ->getMock();
  709. $this->collection->registerMiddleware('callable', $mock);
  710. $this->collection->applyMiddleware('/api', ['callable', 'bad']);
  711. }
  712. }