PaginatorComponentTest.php 42 KB

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