PaginatorComponentTest.php 42 KB

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