PaginatorComponentTest.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  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 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\ComponentRegistry;
  17. use Cake\Controller\Component\PaginatorComponent;
  18. use Cake\Controller\Controller;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\Datasource\EntityInterface;
  21. use Cake\Datasource\Paginator;
  22. use Cake\Http\ServerRequest;
  23. use Cake\Network\Exception\NotFoundException;
  24. use Cake\ORM\Entity;
  25. use Cake\ORM\TableRegistry;
  26. use Cake\TestSuite\TestCase;
  27. /**
  28. * PaginatorTestController class
  29. */
  30. class PaginatorTestController extends Controller
  31. {
  32. /**
  33. * components property
  34. *
  35. * @var array
  36. */
  37. public $components = ['Paginator'];
  38. }
  39. /**
  40. * Custom paginator
  41. */
  42. class CustomPaginator extends Paginator
  43. {
  44. }
  45. class PaginatorComponentTest extends TestCase
  46. {
  47. /**
  48. * fixtures property
  49. *
  50. * @var array
  51. */
  52. public $fixtures = [
  53. 'core.posts', 'core.articles', 'core.articles_tags',
  54. 'core.authors', 'core.authors_tags', 'core.tags'
  55. ];
  56. /**
  57. * Don't load data for fixtures for all tests
  58. *
  59. * @var bool
  60. */
  61. public $autoFixtures = false;
  62. /**
  63. * setup
  64. *
  65. * @return void
  66. */
  67. public function setUp()
  68. {
  69. parent::setUp();
  70. static::setAppNamespace();
  71. $this->request = new ServerRequest('controller_posts/index');
  72. $this->request->params['pass'] = [];
  73. $controller = new Controller($this->request);
  74. $this->registry = new ComponentRegistry($controller);
  75. $this->Paginator = new PaginatorComponent($this->registry, []);
  76. $this->Post = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')
  77. ->disableOriginalConstructor()
  78. ->getMock();
  79. }
  80. /**
  81. * tearDown
  82. *
  83. * @return void
  84. */
  85. public function tearDown()
  86. {
  87. parent::tearDown();
  88. TableRegistry::clear();
  89. }
  90. /**
  91. * testPaginatorSetting
  92. *
  93. * @return void
  94. */
  95. public function testPaginatorSetting()
  96. {
  97. $paginator = new CustomPaginator();
  98. $component = new PaginatorComponent($this->registry, [
  99. 'paginator' => $paginator
  100. ]);
  101. $this->assertSame($paginator, $component->getPaginator());
  102. $component = new PaginatorComponent($this->registry, []);
  103. $this->assertNotSame($paginator, $component->getPaginator());
  104. $component->setPaginator($paginator);
  105. $this->assertSame($paginator, $component->getPaginator());
  106. }
  107. /**
  108. * Test that non-numeric values are rejected for page, and limit
  109. *
  110. * @return void
  111. */
  112. public function testPageParamCasting()
  113. {
  114. $this->Post->expects($this->any())
  115. ->method('alias')
  116. ->will($this->returnValue('Posts'));
  117. $query = $this->_getMockFindQuery();
  118. $this->Post->expects($this->any())
  119. ->method('find')
  120. ->will($this->returnValue($query));
  121. $this->request->query = ['page' => '1 " onclick="alert(\'xss\');">'];
  122. $settings = ['limit' => 1, 'maxLimit' => 10];
  123. $this->Paginator->paginate($this->Post, $settings);
  124. $this->assertSame(1, $this->request->params['paging']['Posts']['page'], 'XSS exploit opened');
  125. }
  126. /**
  127. * test that unknown keys in the default settings are
  128. * passed to the find operations.
  129. *
  130. * @return void
  131. */
  132. public function testPaginateExtraParams()
  133. {
  134. $this->request->query = ['page' => '-1'];
  135. $settings = [
  136. 'PaginatorPosts' => [
  137. 'contain' => ['PaginatorAuthor'],
  138. 'maxLimit' => 10,
  139. 'group' => 'PaginatorPosts.published',
  140. 'order' => ['PaginatorPosts.id' => 'ASC']
  141. ],
  142. ];
  143. $table = $this->_getMockPosts(['query']);
  144. $query = $this->_getMockFindQuery();
  145. $table->expects($this->once())
  146. ->method('query')
  147. ->will($this->returnValue($query));
  148. $query->expects($this->once())
  149. ->method('applyOptions')
  150. ->with([
  151. 'contain' => ['PaginatorAuthor'],
  152. 'group' => 'PaginatorPosts.published',
  153. 'limit' => 10,
  154. 'order' => ['PaginatorPosts.id' => 'ASC'],
  155. 'page' => 1,
  156. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  157. 'scope' => null,
  158. ]);
  159. $this->Paginator->paginate($table, $settings);
  160. }
  161. /**
  162. * Test to make sure options get sent to custom finder methods via paginate
  163. *
  164. * @return void
  165. */
  166. public function testPaginateCustomFinderOptions()
  167. {
  168. $this->loadFixtures('Posts');
  169. $settings = [
  170. 'PaginatorPosts' => [
  171. 'finder' => ['author' => ['author_id' => 1]]
  172. ]
  173. ];
  174. $table = TableRegistry::get('PaginatorPosts');
  175. $expected = $table
  176. ->find('author', [
  177. 'conditions' => [
  178. 'PaginatorPosts.author_id' => 1
  179. ]
  180. ])
  181. ->count();
  182. $result = $this->Paginator->paginate($table, $settings)->count();
  183. $this->assertEquals($expected, $result);
  184. }
  185. /**
  186. * Test that special paginate types are called and that the type param doesn't leak out into defaults or options.
  187. *
  188. * @return void
  189. */
  190. public function testPaginateCustomFinder()
  191. {
  192. $settings = [
  193. 'PaginatorPosts' => [
  194. 'finder' => 'popular',
  195. 'fields' => ['id', 'title'],
  196. 'maxLimit' => 10,
  197. ]
  198. ];
  199. $table = $this->_getMockPosts(['findPopular']);
  200. $query = $this->_getMockFindQuery();
  201. $table->expects($this->any())
  202. ->method('findPopular')
  203. ->will($this->returnValue($query));
  204. $this->Paginator->paginate($table, $settings);
  205. $this->assertEquals('popular', $this->request->params['paging']['PaginatorPosts']['finder']);
  206. }
  207. /**
  208. * Test that nested eager loaders don't trigger invalid SQL errors.
  209. *
  210. * @return void
  211. */
  212. public function testPaginateNestedEagerLoader()
  213. {
  214. $this->loadFixtures('Articles', 'Tags', 'Authors', 'ArticlesTags', 'AuthorsTags');
  215. $articles = TableRegistry::get('Articles');
  216. $articles->belongsToMany('Tags');
  217. $tags = TableRegistry::get('Tags');
  218. $tags->belongsToMany('Authors');
  219. $articles->eventManager()->on('Model.beforeFind', function ($event, $query) {
  220. $query ->matching('Tags', function ($q) {
  221. return $q->matching('Authors', function ($q) {
  222. return $q->where(['Authors.name' => 'larry']);
  223. });
  224. });
  225. });
  226. $results = $this->Paginator->paginate($articles, []);
  227. $result = $results->first();
  228. $this->assertInstanceOf(EntityInterface::class, $result);
  229. $this->assertInstanceOf(EntityInterface::class, $result->_matchingData['Tags']);
  230. $this->assertInstanceOf(EntityInterface::class, $result->_matchingData['Authors']);
  231. }
  232. /**
  233. * test that flat default pagination parameters work.
  234. *
  235. * @return void
  236. */
  237. public function testDefaultPaginateParams()
  238. {
  239. $settings = [
  240. 'order' => ['PaginatorPosts.id' => 'DESC'],
  241. 'maxLimit' => 10,
  242. ];
  243. $table = $this->_getMockPosts(['query']);
  244. $query = $this->_getMockFindQuery();
  245. $table->expects($this->once())
  246. ->method('query')
  247. ->will($this->returnValue($query));
  248. $query->expects($this->once())
  249. ->method('applyOptions')
  250. ->with([
  251. 'limit' => 10,
  252. 'page' => 1,
  253. 'order' => ['PaginatorPosts.id' => 'DESC'],
  254. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  255. 'scope' => null,
  256. ]);
  257. $this->Paginator->paginate($table, $settings);
  258. }
  259. /**
  260. * test that default sort and default direction are injected into request
  261. *
  262. * @return void
  263. */
  264. public function testDefaultPaginateParamsIntoRequest()
  265. {
  266. $settings = [
  267. 'order' => ['PaginatorPosts.id' => 'DESC'],
  268. 'maxLimit' => 10,
  269. ];
  270. $table = $this->_getMockPosts(['query']);
  271. $query = $this->_getMockFindQuery();
  272. $table->expects($this->once())
  273. ->method('query')
  274. ->will($this->returnValue($query));
  275. $query->expects($this->once())
  276. ->method('applyOptions')
  277. ->with([
  278. 'limit' => 10,
  279. 'page' => 1,
  280. 'order' => ['PaginatorPosts.id' => 'DESC'],
  281. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  282. 'scope' => null,
  283. ]);
  284. $this->Paginator->paginate($table, $settings);
  285. $this->assertEquals('PaginatorPosts.id', $this->request->params['paging']['PaginatorPosts']['sortDefault']);
  286. $this->assertEquals('DESC', $this->request->params['paging']['PaginatorPosts']['directionDefault']);
  287. }
  288. /**
  289. * test that option merging prefers specific models
  290. *
  291. * @return void
  292. */
  293. public function testMergeOptionsModelSpecific()
  294. {
  295. $settings = [
  296. 'page' => 1,
  297. 'limit' => 20,
  298. 'maxLimit' => 100,
  299. 'Posts' => [
  300. 'page' => 1,
  301. 'limit' => 10,
  302. 'maxLimit' => 50,
  303. ],
  304. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  305. ];
  306. $result = $this->Paginator->mergeOptions('Silly', $settings);
  307. $this->assertEquals($settings, $result);
  308. $result = $this->Paginator->mergeOptions('Posts', $settings);
  309. $expected = ['page' => 1, 'limit' => 10, 'maxLimit' => 50, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  310. $this->assertEquals($expected, $result);
  311. }
  312. /**
  313. * test mergeOptions with custom scope
  314. *
  315. * @return void
  316. */
  317. public function testMergeOptionsCustomScope()
  318. {
  319. $this->request->query = [
  320. 'page' => 10,
  321. 'limit' => 10,
  322. 'scope' => [
  323. 'page' => 2,
  324. 'limit' => 5,
  325. ]
  326. ];
  327. $settings = [
  328. 'page' => 1,
  329. 'limit' => 20,
  330. 'maxLimit' => 100,
  331. 'finder' => 'myCustomFind',
  332. ];
  333. $result = $this->Paginator->mergeOptions('Post', $settings);
  334. $expected = [
  335. 'page' => 10,
  336. 'limit' => 10,
  337. 'maxLimit' => 100,
  338. 'finder' => 'myCustomFind',
  339. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  340. ];
  341. $this->assertEquals($expected, $result);
  342. $settings = [
  343. 'page' => 1,
  344. 'limit' => 20,
  345. 'maxLimit' => 100,
  346. 'finder' => 'myCustomFind',
  347. 'scope' => 'non-existent',
  348. ];
  349. $result = $this->Paginator->mergeOptions('Post', $settings);
  350. $expected = [
  351. 'page' => 1,
  352. 'limit' => 20,
  353. 'maxLimit' => 100,
  354. 'finder' => 'myCustomFind',
  355. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  356. 'scope' => 'non-existent',
  357. ];
  358. $this->assertEquals($expected, $result);
  359. $settings = [
  360. 'page' => 1,
  361. 'limit' => 20,
  362. 'maxLimit' => 100,
  363. 'finder' => 'myCustomFind',
  364. 'scope' => 'scope',
  365. ];
  366. $result = $this->Paginator->mergeOptions('Post', $settings);
  367. $expected = [
  368. 'page' => 2,
  369. 'limit' => 5,
  370. 'maxLimit' => 100,
  371. 'finder' => 'myCustomFind',
  372. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  373. 'scope' => 'scope',
  374. ];
  375. $this->assertEquals($expected, $result);
  376. }
  377. /**
  378. * test mergeOptions with customFind key
  379. *
  380. * @return void
  381. */
  382. public function testMergeOptionsCustomFindKey()
  383. {
  384. $this->request->query = [
  385. 'page' => 10,
  386. 'limit' => 10
  387. ];
  388. $settings = [
  389. 'page' => 1,
  390. 'limit' => 20,
  391. 'maxLimit' => 100,
  392. 'finder' => 'myCustomFind'
  393. ];
  394. $result = $this->Paginator->mergeOptions('Post', $settings);
  395. $expected = [
  396. 'page' => 10,
  397. 'limit' => 10,
  398. 'maxLimit' => 100,
  399. 'finder' => 'myCustomFind',
  400. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  401. ];
  402. $this->assertEquals($expected, $result);
  403. }
  404. /**
  405. * test merging options from the querystring.
  406. *
  407. * @return void
  408. */
  409. public function testMergeOptionsQueryString()
  410. {
  411. $this->request->query = [
  412. 'page' => 99,
  413. 'limit' => 75
  414. ];
  415. $settings = [
  416. 'page' => 1,
  417. 'limit' => 20,
  418. 'maxLimit' => 100,
  419. ];
  420. $result = $this->Paginator->mergeOptions('Post', $settings);
  421. $expected = ['page' => 99, 'limit' => 75, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  422. $this->assertEquals($expected, $result);
  423. }
  424. /**
  425. * test that the default whitelist doesn't let people screw with things they should not be allowed to.
  426. *
  427. * @return void
  428. */
  429. public function testMergeOptionsDefaultWhiteList()
  430. {
  431. $this->request->query = [
  432. 'page' => 10,
  433. 'limit' => 10,
  434. 'fields' => ['bad.stuff'],
  435. 'recursive' => 1000,
  436. 'conditions' => ['bad.stuff'],
  437. 'contain' => ['bad']
  438. ];
  439. $settings = [
  440. 'page' => 1,
  441. 'limit' => 20,
  442. 'maxLimit' => 100,
  443. ];
  444. $result = $this->Paginator->mergeOptions('Post', $settings);
  445. $expected = ['page' => 10, 'limit' => 10, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  446. $this->assertEquals($expected, $result);
  447. }
  448. /**
  449. * test that modifying the whitelist works.
  450. *
  451. * @return void
  452. */
  453. public function testMergeOptionsExtraWhitelist()
  454. {
  455. $this->request->query = [
  456. 'page' => 10,
  457. 'limit' => 10,
  458. 'fields' => ['bad.stuff'],
  459. 'recursive' => 1000,
  460. 'conditions' => ['bad.stuff'],
  461. 'contain' => ['bad']
  462. ];
  463. $settings = [
  464. 'page' => 1,
  465. 'limit' => 20,
  466. 'maxLimit' => 100,
  467. ];
  468. $this->Paginator->config('whitelist', ['fields']);
  469. $result = $this->Paginator->mergeOptions('Post', $settings);
  470. $expected = [
  471. 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'fields' => ['bad.stuff'], 'whitelist' => ['limit', 'sort', 'page', 'direction', 'fields']
  472. ];
  473. $this->assertEquals($expected, $result);
  474. }
  475. /**
  476. * test mergeOptions with limit > maxLimit in code.
  477. *
  478. * @return void
  479. */
  480. public function testMergeOptionsMaxLimit()
  481. {
  482. $settings = [
  483. 'limit' => 200,
  484. 'paramType' => 'named',
  485. ];
  486. $result = $this->Paginator->mergeOptions('Post', $settings);
  487. $expected = [
  488. 'page' => 1,
  489. 'limit' => 100,
  490. 'maxLimit' => 100,
  491. 'paramType' => 'named',
  492. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  493. ];
  494. $this->assertEquals($expected, $result);
  495. $settings = [
  496. 'maxLimit' => 10,
  497. 'paramType' => 'named',
  498. ];
  499. $result = $this->Paginator->mergeOptions('Post', $settings);
  500. $expected = [
  501. 'page' => 1,
  502. 'limit' => 10,
  503. 'maxLimit' => 10,
  504. 'paramType' => 'named',
  505. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  506. ];
  507. $this->assertEquals($expected, $result);
  508. }
  509. /**
  510. * test getDefaults with limit > maxLimit in code.
  511. *
  512. * @return void
  513. */
  514. public function testGetDefaultMaxLimit()
  515. {
  516. $settings = [
  517. 'page' => 1,
  518. 'limit' => 2,
  519. 'maxLimit' => 10,
  520. 'order' => [
  521. 'Users.username' => 'asc'
  522. ],
  523. ];
  524. $result = $this->Paginator->mergeOptions('Post', $settings);
  525. $expected = [
  526. 'page' => 1,
  527. 'limit' => 2,
  528. 'maxLimit' => 10,
  529. 'order' => [
  530. 'Users.username' => 'asc'
  531. ],
  532. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  533. ];
  534. $this->assertEquals($expected, $result);
  535. $settings = [
  536. 'page' => 1,
  537. 'limit' => 100,
  538. 'maxLimit' => 10,
  539. 'order' => [
  540. 'Users.username' => 'asc'
  541. ],
  542. ];
  543. $result = $this->Paginator->mergeOptions('Post', $settings);
  544. $expected = [
  545. 'page' => 1,
  546. 'limit' => 10,
  547. 'maxLimit' => 10,
  548. 'order' => [
  549. 'Users.username' => 'asc'
  550. ],
  551. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  552. ];
  553. $this->assertEquals($expected, $result);
  554. }
  555. /**
  556. * Integration test to ensure that validateSort is being used by paginate()
  557. *
  558. * @return void
  559. */
  560. public function testValidateSortInvalid()
  561. {
  562. $table = $this->_getMockPosts(['query']);
  563. $query = $this->_getMockFindQuery();
  564. $table->expects($this->once())
  565. ->method('query')
  566. ->will($this->returnValue($query));
  567. $query->expects($this->once())->method('applyOptions')
  568. ->with([
  569. 'limit' => 20,
  570. 'page' => 1,
  571. 'order' => ['PaginatorPosts.id' => 'asc'],
  572. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  573. 'scope' => null,
  574. ]);
  575. $this->request->query = [
  576. 'page' => 1,
  577. 'sort' => 'id',
  578. 'direction' => 'herp'
  579. ];
  580. $this->Paginator->paginate($table);
  581. $this->assertEquals('PaginatorPosts.id', $this->request->params['paging']['PaginatorPosts']['sort']);
  582. $this->assertEquals('asc', $this->request->params['paging']['PaginatorPosts']['direction']);
  583. }
  584. /**
  585. * test that invalid directions are ignored.
  586. *
  587. * @return void
  588. */
  589. public function testValidateSortInvalidDirection()
  590. {
  591. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  592. $model->expects($this->any())
  593. ->method('alias')
  594. ->will($this->returnValue('model'));
  595. $model->expects($this->any())
  596. ->method('hasField')
  597. ->will($this->returnValue(true));
  598. $options = ['sort' => 'something', 'direction' => 'boogers'];
  599. $result = $this->Paginator->validateSort($model, $options);
  600. $this->assertEquals('asc', $result['order']['model.something']);
  601. }
  602. /**
  603. * Test that a really large page number gets clamped to the max page size.
  604. *
  605. * @return void
  606. */
  607. public function testOutOfRangePageNumberGetsClamped()
  608. {
  609. $this->loadFixtures('Posts');
  610. $this->request->query['page'] = 3000;
  611. $table = TableRegistry::get('PaginatorPosts');
  612. try {
  613. $this->Paginator->paginate($table);
  614. $this->fail('No exception raised');
  615. } catch (NotFoundException $e) {
  616. $this->assertEquals(
  617. 1,
  618. $this->request->params['paging']['PaginatorPosts']['page'],
  619. 'Page number should not be 0'
  620. );
  621. }
  622. }
  623. /**
  624. * Test that a really REALLY large page number gets clamped to the max page size.
  625. *
  626. * @expectedException \Cake\Network\Exception\NotFoundException
  627. * @return void
  628. */
  629. public function testOutOfVeryBigPageNumberGetsClamped()
  630. {
  631. $this->loadFixtures('Posts');
  632. $this->request->query = [
  633. 'page' => '3000000000000000000000000',
  634. ];
  635. $table = TableRegistry::get('PaginatorPosts');
  636. $this->Paginator->paginate($table);
  637. }
  638. /**
  639. * test that fields not in whitelist won't be part of order conditions.
  640. *
  641. * @return void
  642. */
  643. public function testValidateSortWhitelistFailure()
  644. {
  645. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  646. $model->expects($this->any())
  647. ->method('alias')
  648. ->will($this->returnValue('model'));
  649. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  650. $options = [
  651. 'sort' => 'body',
  652. 'direction' => 'asc',
  653. 'sortWhitelist' => ['title', 'id']
  654. ];
  655. $result = $this->Paginator->validateSort($model, $options);
  656. $this->assertEquals([], $result['order']);
  657. }
  658. /**
  659. * test that fields in the whitelist are not validated
  660. *
  661. * @return void
  662. */
  663. public function testValidateSortWhitelistTrusted()
  664. {
  665. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  666. $model->expects($this->any())
  667. ->method('alias')
  668. ->will($this->returnValue('model'));
  669. $model->expects($this->once())
  670. ->method('hasField')
  671. ->will($this->returnValue(true));
  672. $options = [
  673. 'sort' => 'body',
  674. 'direction' => 'asc',
  675. 'sortWhitelist' => ['body']
  676. ];
  677. $result = $this->Paginator->validateSort($model, $options);
  678. $expected = ['model.body' => 'asc'];
  679. $this->assertEquals(
  680. $expected,
  681. $result['order'],
  682. 'Trusted fields in schema should be prefixed'
  683. );
  684. }
  685. /**
  686. * test that whitelist as empty array does not allow any sorting
  687. *
  688. * @return void
  689. */
  690. public function testValidateSortWhitelistEmpty()
  691. {
  692. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  693. $model->expects($this->any())
  694. ->method('alias')
  695. ->will($this->returnValue('model'));
  696. $model->expects($this->any())->method('hasField')
  697. ->will($this->returnValue(true));
  698. $options = [
  699. 'order' => [
  700. 'body' => 'asc',
  701. 'foo.bar' => 'asc'
  702. ],
  703. 'sort' => 'body',
  704. 'direction' => 'asc',
  705. 'sortWhitelist' => []
  706. ];
  707. $result = $this->Paginator->validateSort($model, $options);
  708. $this->assertSame([], $result['order'], 'No sort should be applied');
  709. }
  710. /**
  711. * test that fields in the whitelist are not validated
  712. *
  713. * @return void
  714. */
  715. public function testValidateSortWhitelistNotInSchema()
  716. {
  717. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  718. $model->expects($this->any())
  719. ->method('alias')
  720. ->will($this->returnValue('model'));
  721. $model->expects($this->once())->method('hasField')
  722. ->will($this->returnValue(false));
  723. $options = [
  724. 'sort' => 'score',
  725. 'direction' => 'asc',
  726. 'sortWhitelist' => ['score']
  727. ];
  728. $result = $this->Paginator->validateSort($model, $options);
  729. $expected = ['score' => 'asc'];
  730. $this->assertEquals(
  731. $expected,
  732. $result['order'],
  733. 'Trusted fields not in schema should not be altered'
  734. );
  735. }
  736. /**
  737. * test that multiple fields in the whitelist are not validated and properly aliased.
  738. *
  739. * @return void
  740. */
  741. public function testValidateSortWhitelistMultiple()
  742. {
  743. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  744. $model->expects($this->any())
  745. ->method('alias')
  746. ->will($this->returnValue('model'));
  747. $model->expects($this->once())
  748. ->method('hasField')
  749. ->will($this->returnValue(true));
  750. $options = [
  751. 'order' => [
  752. 'body' => 'asc',
  753. 'foo.bar' => 'asc'
  754. ],
  755. 'sortWhitelist' => ['body', 'foo.bar']
  756. ];
  757. $result = $this->Paginator->validateSort($model, $options);
  758. $expected = [
  759. 'model.body' => 'asc',
  760. 'foo.bar' => 'asc'
  761. ];
  762. $this->assertEquals($expected, $result['order']);
  763. }
  764. /**
  765. * test that multiple sort works.
  766. *
  767. * @return void
  768. */
  769. public function testValidateSortMultiple()
  770. {
  771. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  772. $model->expects($this->any())
  773. ->method('alias')
  774. ->will($this->returnValue('model'));
  775. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  776. $options = [
  777. 'order' => [
  778. 'author_id' => 'asc',
  779. 'title' => 'asc'
  780. ]
  781. ];
  782. $result = $this->Paginator->validateSort($model, $options);
  783. $expected = [
  784. 'model.author_id' => 'asc',
  785. 'model.title' => 'asc'
  786. ];
  787. $this->assertEquals($expected, $result['order']);
  788. }
  789. /**
  790. * Tests that order strings can used by Paginator
  791. *
  792. * @return void
  793. */
  794. public function testValidateSortWithString()
  795. {
  796. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  797. $model->expects($this->any())
  798. ->method('alias')
  799. ->will($this->returnValue('model'));
  800. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  801. $options = [
  802. 'order' => 'model.author_id DESC'
  803. ];
  804. $result = $this->Paginator->validateSort($model, $options);
  805. $expected = 'model.author_id DESC';
  806. $this->assertEquals($expected, $result['order']);
  807. }
  808. /**
  809. * Test that no sort doesn't trigger an error.
  810. *
  811. * @return void
  812. */
  813. public function testValidateSortNoSort()
  814. {
  815. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  816. $model->expects($this->any())
  817. ->method('alias')
  818. ->will($this->returnValue('model'));
  819. $model->expects($this->any())->method('hasField')
  820. ->will($this->returnValue(true));
  821. $options = [
  822. 'direction' => 'asc',
  823. 'sortWhitelist' => ['title', 'id'],
  824. ];
  825. $result = $this->Paginator->validateSort($model, $options);
  826. $this->assertEquals([], $result['order']);
  827. }
  828. /**
  829. * Test sorting with incorrect aliases on valid fields.
  830. *
  831. * @return void
  832. */
  833. public function testValidateSortInvalidAlias()
  834. {
  835. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  836. $model->expects($this->any())
  837. ->method('alias')
  838. ->will($this->returnValue('model'));
  839. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  840. $options = ['sort' => 'Derp.id'];
  841. $result = $this->Paginator->validateSort($model, $options);
  842. $this->assertEquals([], $result['order']);
  843. }
  844. /**
  845. * @return array
  846. */
  847. public function checkLimitProvider()
  848. {
  849. return [
  850. 'out of bounds' => [
  851. ['limit' => 1000000, 'maxLimit' => 100],
  852. 100,
  853. ],
  854. 'limit is nan' => [
  855. ['limit' => 'sheep!', 'maxLimit' => 100],
  856. 1,
  857. ],
  858. 'negative limit' => [
  859. ['limit' => '-1', 'maxLimit' => 100],
  860. 1,
  861. ],
  862. 'unset limit' => [
  863. ['limit' => null, 'maxLimit' => 100],
  864. 1,
  865. ],
  866. 'limit = 0' => [
  867. ['limit' => 0, 'maxLimit' => 100],
  868. 1,
  869. ],
  870. 'limit = 0 v2' => [
  871. ['limit' => 0, 'maxLimit' => 0],
  872. 1,
  873. ],
  874. 'limit = null' => [
  875. ['limit' => null, 'maxLimit' => 0],
  876. 1,
  877. ],
  878. 'bad input, results in 1' => [
  879. ['limit' => null, 'maxLimit' => null],
  880. 1,
  881. ],
  882. 'bad input, results in 1 v2' => [
  883. ['limit' => false, 'maxLimit' => false],
  884. 1,
  885. ],
  886. ];
  887. }
  888. /**
  889. * test that maxLimit is respected
  890. *
  891. * @dataProvider checkLimitProvider
  892. * @return void
  893. */
  894. public function testCheckLimit($input, $expected)
  895. {
  896. $result = $this->Paginator->checkLimit($input);
  897. $this->assertSame($expected, $result['limit']);
  898. }
  899. /**
  900. * Integration test for checkLimit() being applied inside paginate()
  901. *
  902. * @return void
  903. */
  904. public function testPaginateMaxLimit()
  905. {
  906. $this->loadFixtures('Posts');
  907. $table = TableRegistry::get('PaginatorPosts');
  908. $settings = [
  909. 'maxLimit' => 100,
  910. ];
  911. $this->request->query = [
  912. 'limit' => '1000'
  913. ];
  914. $this->Paginator->paginate($table, $settings);
  915. $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['limit']);
  916. $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['perPage']);
  917. $this->request->query = [
  918. 'limit' => '10'
  919. ];
  920. $this->Paginator->paginate($table, $settings);
  921. $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['limit']);
  922. $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['perPage']);
  923. }
  924. /**
  925. * test paginate() and custom find, to make sure the correct count is returned.
  926. *
  927. * @return void
  928. */
  929. public function testPaginateCustomFind()
  930. {
  931. $this->loadFixtures('Posts');
  932. $titleExtractor = function ($result) {
  933. $ids = [];
  934. foreach ($result as $record) {
  935. $ids[] = $record->title;
  936. }
  937. return $ids;
  938. };
  939. $table = TableRegistry::get('PaginatorPosts');
  940. $data = ['author_id' => 3, 'title' => 'Fourth Post', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  941. $result = $table->save(new Entity($data));
  942. $this->assertNotEmpty($result);
  943. $result = $this->Paginator->paginate($table);
  944. $this->assertCount(4, $result, '4 rows should come back');
  945. $this->assertEquals(['First Post', 'Second Post', 'Third Post', 'Fourth Post'], $titleExtractor($result));
  946. $result = $this->request->params['paging']['PaginatorPosts'];
  947. $this->assertEquals(4, $result['current']);
  948. $this->assertEquals(4, $result['count']);
  949. $settings = ['finder' => 'published'];
  950. $result = $this->Paginator->paginate($table, $settings);
  951. $this->assertCount(3, $result, '3 rows should come back');
  952. $this->assertEquals(['First Post', 'Second Post', 'Third Post'], $titleExtractor($result));
  953. $result = $this->request->params['paging']['PaginatorPosts'];
  954. $this->assertEquals(3, $result['current']);
  955. $this->assertEquals(3, $result['count']);
  956. $settings = ['finder' => 'published', 'limit' => 2, 'page' => 2];
  957. $result = $this->Paginator->paginate($table, $settings);
  958. $this->assertCount(1, $result, '1 rows should come back');
  959. $this->assertEquals(['Third Post'], $titleExtractor($result));
  960. $result = $this->request->params['paging']['PaginatorPosts'];
  961. $this->assertEquals(1, $result['current']);
  962. $this->assertEquals(3, $result['count']);
  963. $this->assertEquals(2, $result['pageCount']);
  964. $settings = ['finder' => 'published', 'limit' => 2];
  965. $result = $this->Paginator->paginate($table, $settings);
  966. $this->assertCount(2, $result, '2 rows should come back');
  967. $this->assertEquals(['First Post', 'Second Post'], $titleExtractor($result));
  968. $result = $this->request->params['paging']['PaginatorPosts'];
  969. $this->assertEquals(2, $result['current']);
  970. $this->assertEquals(3, $result['count']);
  971. $this->assertEquals(2, $result['pageCount']);
  972. $this->assertTrue($result['nextPage']);
  973. $this->assertFalse($result['prevPage']);
  974. $this->assertEquals(2, $result['perPage']);
  975. $this->assertNull($result['limit']);
  976. }
  977. /**
  978. * test paginate() and custom find with fields array, to make sure the correct count is returned.
  979. *
  980. * @return void
  981. */
  982. public function testPaginateCustomFindFieldsArray()
  983. {
  984. $this->loadFixtures('Posts');
  985. $table = TableRegistry::get('PaginatorPosts');
  986. $data = ['author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  987. $table->save(new Entity($data));
  988. $settings = [
  989. 'finder' => 'list',
  990. 'conditions' => ['PaginatorPosts.published' => 'Y'],
  991. 'limit' => 2
  992. ];
  993. $results = $this->Paginator->paginate($table, $settings);
  994. $result = $results->toArray();
  995. $expected = [
  996. 1 => 'First Post',
  997. 2 => 'Second Post',
  998. ];
  999. $this->assertEquals($expected, $result);
  1000. $result = $this->request->params['paging']['PaginatorPosts'];
  1001. $this->assertEquals(2, $result['current']);
  1002. $this->assertEquals(3, $result['count']);
  1003. $this->assertEquals(2, $result['pageCount']);
  1004. $this->assertTrue($result['nextPage']);
  1005. $this->assertFalse($result['prevPage']);
  1006. }
  1007. /**
  1008. * test paginate() and custom finders to ensure the count + find
  1009. * use the custom type.
  1010. *
  1011. * @return void
  1012. */
  1013. public function testPaginateCustomFindCount()
  1014. {
  1015. $settings = [
  1016. 'finder' => 'published',
  1017. 'limit' => 2
  1018. ];
  1019. $table = $this->_getMockPosts(['query']);
  1020. $query = $this->_getMockFindQuery();
  1021. $table->expects($this->once())
  1022. ->method('query')
  1023. ->will($this->returnValue($query));
  1024. $query->expects($this->once())->method('applyOptions')
  1025. ->with([
  1026. 'limit' => 2,
  1027. 'page' => 1,
  1028. 'order' => [],
  1029. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1030. 'scope' => null,
  1031. ]);
  1032. $this->Paginator->paginate($table, $settings);
  1033. }
  1034. /**
  1035. * Tests that it is possible to pass an already made query object to
  1036. * paginate()
  1037. *
  1038. * @return void
  1039. */
  1040. public function testPaginateQuery()
  1041. {
  1042. $this->request->query = ['page' => '-1'];
  1043. $settings = [
  1044. 'PaginatorPosts' => [
  1045. 'contain' => ['PaginatorAuthor'],
  1046. 'maxLimit' => 10,
  1047. 'group' => 'PaginatorPosts.published',
  1048. 'order' => ['PaginatorPosts.id' => 'ASC']
  1049. ]
  1050. ];
  1051. $table = $this->_getMockPosts(['find']);
  1052. $query = $this->_getMockFindQuery($table);
  1053. $table->expects($this->never())->method('find');
  1054. $query->expects($this->once())
  1055. ->method('applyOptions')
  1056. ->with([
  1057. 'contain' => ['PaginatorAuthor'],
  1058. 'group' => 'PaginatorPosts.published',
  1059. 'limit' => 10,
  1060. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1061. 'page' => 1,
  1062. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1063. 'scope' => null,
  1064. ]);
  1065. $this->Paginator->paginate($query, $settings);
  1066. }
  1067. /**
  1068. * test paginate() with bind()
  1069. *
  1070. * @return void
  1071. */
  1072. public function testPaginateQueryWithBindValue()
  1073. {
  1074. $config = ConnectionManager::config('test');
  1075. $this->skipIf(strpos($config['driver'], 'Sqlserver') !== false, 'Test temporarily broken in SQLServer');
  1076. $this->loadFixtures('Posts');
  1077. $table = TableRegistry::get('PaginatorPosts');
  1078. $query = $table->find()
  1079. ->where(['PaginatorPosts.author_id BETWEEN :start AND :end'])
  1080. ->bind(':start', 1)
  1081. ->bind(':end', 2);
  1082. $results = $this->Paginator->paginate($query, []);
  1083. $result = $results->toArray();
  1084. $this->assertCount(2, $result);
  1085. $this->assertEquals('First Post', $result[0]->title);
  1086. $this->assertEquals('Third Post', $result[1]->title);
  1087. }
  1088. /**
  1089. * Tests that passing a query object with a limit clause set will
  1090. * overwrite it with the passed defaults.
  1091. *
  1092. * @return void
  1093. */
  1094. public function testPaginateQueryWithLimit()
  1095. {
  1096. $this->request->query = ['page' => '-1'];
  1097. $settings = [
  1098. 'PaginatorPosts' => [
  1099. 'contain' => ['PaginatorAuthor'],
  1100. 'maxLimit' => 10,
  1101. 'limit' => 5,
  1102. 'group' => 'PaginatorPosts.published',
  1103. 'order' => ['PaginatorPosts.id' => 'ASC']
  1104. ]
  1105. ];
  1106. $table = $this->_getMockPosts(['find']);
  1107. $query = $this->_getMockFindQuery($table);
  1108. $query->limit(2);
  1109. $table->expects($this->never())->method('find');
  1110. $query->expects($this->once())
  1111. ->method('applyOptions')
  1112. ->with([
  1113. 'contain' => ['PaginatorAuthor'],
  1114. 'group' => 'PaginatorPosts.published',
  1115. 'limit' => 5,
  1116. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1117. 'page' => 1,
  1118. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1119. 'scope' => null,
  1120. ]);
  1121. $this->Paginator->paginate($query, $settings);
  1122. }
  1123. /**
  1124. * Helper method for making mocks.
  1125. *
  1126. * @param array $methods
  1127. * @return \Cake\ORM\Table
  1128. */
  1129. protected function _getMockPosts($methods = [])
  1130. {
  1131. return $this->getMockBuilder('TestApp\Model\Table\PaginatorPostsTable')
  1132. ->setMethods($methods)
  1133. ->setConstructorArgs([[
  1134. 'connection' => ConnectionManager::get('test'),
  1135. 'alias' => 'PaginatorPosts',
  1136. 'schema' => [
  1137. 'id' => ['type' => 'integer'],
  1138. 'author_id' => ['type' => 'integer', 'null' => false],
  1139. 'title' => ['type' => 'string', 'null' => false],
  1140. 'body' => 'text',
  1141. 'published' => ['type' => 'string', 'length' => 1, 'default' => 'N'],
  1142. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  1143. ]
  1144. ]])
  1145. ->getMock();
  1146. }
  1147. /**
  1148. * Helper method for mocking queries.
  1149. *
  1150. * @return \Cake\ORM\Query
  1151. */
  1152. protected function _getMockFindQuery($table = null)
  1153. {
  1154. $query = $this->getMockBuilder('Cake\ORM\Query')
  1155. ->setMethods(['total', 'all', 'count', 'applyOptions'])
  1156. ->disableOriginalConstructor()
  1157. ->getMock();
  1158. $results = $this->getMockBuilder('Cake\ORM\ResultSet')
  1159. ->disableOriginalConstructor()
  1160. ->getMock();
  1161. $query->expects($this->any())
  1162. ->method('count')
  1163. ->will($this->returnValue(2));
  1164. $query->expects($this->any())
  1165. ->method('all')
  1166. ->will($this->returnValue($results));
  1167. $query->expects($this->any())
  1168. ->method('count')
  1169. ->will($this->returnValue(2));
  1170. $query->repository($table);
  1171. return $query;
  1172. }
  1173. }