PaginatorTest.php 40 KB

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