PaginatorComponentTest.php 34 KB

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