PaginatorComponentTest.php 40 KB

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