PaginatorComponentTest.php 39 KB

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