PaginatorTest.php 41 KB

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