PaginatorTestTrait.php 41 KB

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