PaginatorComponentTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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 empty pagination result.
  580. *
  581. * @return void
  582. */
  583. public function testEmptyPaginationResult()
  584. {
  585. $this->loadFixtures('Posts');
  586. $table = TableRegistry::get('PaginatorPosts');
  587. $table->deleteAll('1=1');
  588. $this->Paginator->paginate($table);
  589. $this->assertEquals(
  590. 0,
  591. $this->request->params['paging']['PaginatorPosts']['count'],
  592. 'Count should be 0'
  593. );
  594. $this->assertEquals(
  595. 1,
  596. $this->request->params['paging']['PaginatorPosts']['page'],
  597. 'Page number should not be 0'
  598. );
  599. $this->assertEquals(
  600. 1,
  601. $this->request->params['paging']['PaginatorPosts']['pageCount'],
  602. 'Page count number should not be 0'
  603. );
  604. }
  605. /**
  606. * Test that a really large page number gets clamped to the max page size.
  607. *
  608. * @return void
  609. */
  610. public function testOutOfRangePageNumberGetsClamped()
  611. {
  612. $this->loadFixtures('Posts');
  613. $this->request->query['page'] = 3000;
  614. $table = TableRegistry::get('PaginatorPosts');
  615. try {
  616. $this->Paginator->paginate($table);
  617. $this->fail('No exception raised');
  618. } catch (NotFoundException $e) {
  619. $this->assertEquals(
  620. 1,
  621. $this->request->params['paging']['PaginatorPosts']['page'],
  622. 'Page number should not be 0'
  623. );
  624. }
  625. }
  626. /**
  627. * Test that a really REALLY large page number gets clamped to the max page size.
  628. *
  629. * @expectedException \Cake\Network\Exception\NotFoundException
  630. * @return void
  631. */
  632. public function testOutOfVeryBigPageNumberGetsClamped()
  633. {
  634. $this->loadFixtures('Posts');
  635. $this->request->query = [
  636. 'page' => '3000000000000000000000000',
  637. ];
  638. $table = TableRegistry::get('PaginatorPosts');
  639. $this->Paginator->paginate($table);
  640. }
  641. /**
  642. * test that fields not in whitelist won't be part of order conditions.
  643. *
  644. * @return void
  645. */
  646. public function testValidateSortWhitelistFailure()
  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')->will($this->returnValue(true));
  653. $options = [
  654. 'sort' => 'body',
  655. 'direction' => 'asc',
  656. 'sortWhitelist' => ['title', 'id']
  657. ];
  658. $result = $this->Paginator->validateSort($model, $options);
  659. $this->assertEquals([], $result['order']);
  660. }
  661. /**
  662. * test that fields in the whitelist are not validated
  663. *
  664. * @return void
  665. */
  666. public function testValidateSortWhitelistTrusted()
  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->once())
  673. ->method('hasField')
  674. ->will($this->returnValue(true));
  675. $options = [
  676. 'sort' => 'body',
  677. 'direction' => 'asc',
  678. 'sortWhitelist' => ['body']
  679. ];
  680. $result = $this->Paginator->validateSort($model, $options);
  681. $expected = ['model.body' => 'asc'];
  682. $this->assertEquals(
  683. $expected,
  684. $result['order'],
  685. 'Trusted fields in schema should be prefixed'
  686. );
  687. }
  688. /**
  689. * test that whitelist as empty array does not allow any sorting
  690. *
  691. * @return void
  692. */
  693. public function testValidateSortWhitelistEmpty()
  694. {
  695. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  696. $model->expects($this->any())
  697. ->method('alias')
  698. ->will($this->returnValue('model'));
  699. $model->expects($this->any())->method('hasField')
  700. ->will($this->returnValue(true));
  701. $options = [
  702. 'order' => [
  703. 'body' => 'asc',
  704. 'foo.bar' => 'asc'
  705. ],
  706. 'sort' => 'body',
  707. 'direction' => 'asc',
  708. 'sortWhitelist' => []
  709. ];
  710. $result = $this->Paginator->validateSort($model, $options);
  711. $this->assertSame([], $result['order'], 'No sort should be applied');
  712. }
  713. /**
  714. * test that fields in the whitelist are not validated
  715. *
  716. * @return void
  717. */
  718. public function testValidateSortWhitelistNotInSchema()
  719. {
  720. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  721. $model->expects($this->any())
  722. ->method('alias')
  723. ->will($this->returnValue('model'));
  724. $model->expects($this->once())->method('hasField')
  725. ->will($this->returnValue(false));
  726. $options = [
  727. 'sort' => 'score',
  728. 'direction' => 'asc',
  729. 'sortWhitelist' => ['score']
  730. ];
  731. $result = $this->Paginator->validateSort($model, $options);
  732. $expected = ['score' => 'asc'];
  733. $this->assertEquals(
  734. $expected,
  735. $result['order'],
  736. 'Trusted fields not in schema should not be altered'
  737. );
  738. }
  739. /**
  740. * test that multiple fields in the whitelist are not validated and properly aliased.
  741. *
  742. * @return void
  743. */
  744. public function testValidateSortWhitelistMultiple()
  745. {
  746. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  747. $model->expects($this->any())
  748. ->method('alias')
  749. ->will($this->returnValue('model'));
  750. $model->expects($this->once())
  751. ->method('hasField')
  752. ->will($this->returnValue(true));
  753. $options = [
  754. 'order' => [
  755. 'body' => 'asc',
  756. 'foo.bar' => 'asc'
  757. ],
  758. 'sortWhitelist' => ['body', 'foo.bar']
  759. ];
  760. $result = $this->Paginator->validateSort($model, $options);
  761. $expected = [
  762. 'model.body' => 'asc',
  763. 'foo.bar' => 'asc'
  764. ];
  765. $this->assertEquals($expected, $result['order']);
  766. }
  767. /**
  768. * test that multiple sort works.
  769. *
  770. * @return void
  771. */
  772. public function testValidateSortMultiple()
  773. {
  774. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  775. $model->expects($this->any())
  776. ->method('alias')
  777. ->will($this->returnValue('model'));
  778. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  779. $options = [
  780. 'order' => [
  781. 'author_id' => 'asc',
  782. 'title' => 'asc'
  783. ]
  784. ];
  785. $result = $this->Paginator->validateSort($model, $options);
  786. $expected = [
  787. 'model.author_id' => 'asc',
  788. 'model.title' => 'asc'
  789. ];
  790. $this->assertEquals($expected, $result['order']);
  791. }
  792. /**
  793. * Tests that order strings can used by Paginator
  794. *
  795. * @return void
  796. */
  797. public function testValidateSortWithString()
  798. {
  799. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  800. $model->expects($this->any())
  801. ->method('alias')
  802. ->will($this->returnValue('model'));
  803. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  804. $options = [
  805. 'order' => 'model.author_id DESC'
  806. ];
  807. $result = $this->Paginator->validateSort($model, $options);
  808. $expected = 'model.author_id DESC';
  809. $this->assertEquals($expected, $result['order']);
  810. }
  811. /**
  812. * Test that no sort doesn't trigger an error.
  813. *
  814. * @return void
  815. */
  816. public function testValidateSortNoSort()
  817. {
  818. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  819. $model->expects($this->any())
  820. ->method('alias')
  821. ->will($this->returnValue('model'));
  822. $model->expects($this->any())->method('hasField')
  823. ->will($this->returnValue(true));
  824. $options = [
  825. 'direction' => 'asc',
  826. 'sortWhitelist' => ['title', 'id'],
  827. ];
  828. $result = $this->Paginator->validateSort($model, $options);
  829. $this->assertEquals([], $result['order']);
  830. }
  831. /**
  832. * Test sorting with incorrect aliases on valid fields.
  833. *
  834. * @return void
  835. */
  836. public function testValidateSortInvalidAlias()
  837. {
  838. $model = $this->getMockBuilder('Cake\ORM\Table')->getMock();
  839. $model->expects($this->any())
  840. ->method('alias')
  841. ->will($this->returnValue('model'));
  842. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  843. $options = ['sort' => 'Derp.id'];
  844. $result = $this->Paginator->validateSort($model, $options);
  845. $this->assertEquals([], $result['order']);
  846. }
  847. /**
  848. * @return array
  849. */
  850. public function checkLimitProvider()
  851. {
  852. return [
  853. 'out of bounds' => [
  854. ['limit' => 1000000, 'maxLimit' => 100],
  855. 100,
  856. ],
  857. 'limit is nan' => [
  858. ['limit' => 'sheep!', 'maxLimit' => 100],
  859. 1,
  860. ],
  861. 'negative limit' => [
  862. ['limit' => '-1', 'maxLimit' => 100],
  863. 1,
  864. ],
  865. 'unset limit' => [
  866. ['limit' => null, 'maxLimit' => 100],
  867. 1,
  868. ],
  869. 'limit = 0' => [
  870. ['limit' => 0, 'maxLimit' => 100],
  871. 1,
  872. ],
  873. 'limit = 0 v2' => [
  874. ['limit' => 0, 'maxLimit' => 0],
  875. 1,
  876. ],
  877. 'limit = null' => [
  878. ['limit' => null, 'maxLimit' => 0],
  879. 1,
  880. ],
  881. 'bad input, results in 1' => [
  882. ['limit' => null, 'maxLimit' => null],
  883. 1,
  884. ],
  885. 'bad input, results in 1 v2' => [
  886. ['limit' => false, 'maxLimit' => false],
  887. 1,
  888. ],
  889. ];
  890. }
  891. /**
  892. * test that maxLimit is respected
  893. *
  894. * @dataProvider checkLimitProvider
  895. * @return void
  896. */
  897. public function testCheckLimit($input, $expected)
  898. {
  899. $result = $this->Paginator->checkLimit($input);
  900. $this->assertSame($expected, $result['limit']);
  901. }
  902. /**
  903. * Integration test for checkLimit() being applied inside paginate()
  904. *
  905. * @return void
  906. */
  907. public function testPaginateMaxLimit()
  908. {
  909. $this->loadFixtures('Posts');
  910. $table = TableRegistry::get('PaginatorPosts');
  911. $settings = [
  912. 'maxLimit' => 100,
  913. ];
  914. $this->request->query = [
  915. 'limit' => '1000'
  916. ];
  917. $this->Paginator->paginate($table, $settings);
  918. $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['limit']);
  919. $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['perPage']);
  920. $this->request->query = [
  921. 'limit' => '10'
  922. ];
  923. $this->Paginator->paginate($table, $settings);
  924. $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['limit']);
  925. $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['perPage']);
  926. }
  927. /**
  928. * test paginate() and custom find, to make sure the correct count is returned.
  929. *
  930. * @return void
  931. */
  932. public function testPaginateCustomFind()
  933. {
  934. $this->loadFixtures('Posts');
  935. $titleExtractor = function ($result) {
  936. $ids = [];
  937. foreach ($result as $record) {
  938. $ids[] = $record->title;
  939. }
  940. return $ids;
  941. };
  942. $table = TableRegistry::get('PaginatorPosts');
  943. $data = ['author_id' => 3, 'title' => 'Fourth Post', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  944. $result = $table->save(new Entity($data));
  945. $this->assertNotEmpty($result);
  946. $result = $this->Paginator->paginate($table);
  947. $this->assertCount(4, $result, '4 rows should come back');
  948. $this->assertEquals(['First Post', 'Second Post', 'Third Post', 'Fourth Post'], $titleExtractor($result));
  949. $result = $this->request->params['paging']['PaginatorPosts'];
  950. $this->assertEquals(4, $result['current']);
  951. $this->assertEquals(4, $result['count']);
  952. $settings = ['finder' => 'published'];
  953. $result = $this->Paginator->paginate($table, $settings);
  954. $this->assertCount(3, $result, '3 rows should come back');
  955. $this->assertEquals(['First Post', 'Second Post', 'Third Post'], $titleExtractor($result));
  956. $result = $this->request->params['paging']['PaginatorPosts'];
  957. $this->assertEquals(3, $result['current']);
  958. $this->assertEquals(3, $result['count']);
  959. $settings = ['finder' => 'published', 'limit' => 2, 'page' => 2];
  960. $result = $this->Paginator->paginate($table, $settings);
  961. $this->assertCount(1, $result, '1 rows should come back');
  962. $this->assertEquals(['Third Post'], $titleExtractor($result));
  963. $result = $this->request->params['paging']['PaginatorPosts'];
  964. $this->assertEquals(1, $result['current']);
  965. $this->assertEquals(3, $result['count']);
  966. $this->assertEquals(2, $result['pageCount']);
  967. $settings = ['finder' => 'published', 'limit' => 2];
  968. $result = $this->Paginator->paginate($table, $settings);
  969. $this->assertCount(2, $result, '2 rows should come back');
  970. $this->assertEquals(['First Post', 'Second Post'], $titleExtractor($result));
  971. $result = $this->request->params['paging']['PaginatorPosts'];
  972. $this->assertEquals(2, $result['current']);
  973. $this->assertEquals(3, $result['count']);
  974. $this->assertEquals(2, $result['pageCount']);
  975. $this->assertTrue($result['nextPage']);
  976. $this->assertFalse($result['prevPage']);
  977. $this->assertEquals(2, $result['perPage']);
  978. $this->assertNull($result['limit']);
  979. }
  980. /**
  981. * test paginate() and custom find with fields array, to make sure the correct count is returned.
  982. *
  983. * @return void
  984. */
  985. public function testPaginateCustomFindFieldsArray()
  986. {
  987. $this->loadFixtures('Posts');
  988. $table = TableRegistry::get('PaginatorPosts');
  989. $data = ['author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  990. $table->save(new Entity($data));
  991. $settings = [
  992. 'finder' => 'list',
  993. 'conditions' => ['PaginatorPosts.published' => 'Y'],
  994. 'limit' => 2
  995. ];
  996. $results = $this->Paginator->paginate($table, $settings);
  997. $result = $results->toArray();
  998. $expected = [
  999. 1 => 'First Post',
  1000. 2 => 'Second Post',
  1001. ];
  1002. $this->assertEquals($expected, $result);
  1003. $result = $this->request->params['paging']['PaginatorPosts'];
  1004. $this->assertEquals(2, $result['current']);
  1005. $this->assertEquals(3, $result['count']);
  1006. $this->assertEquals(2, $result['pageCount']);
  1007. $this->assertTrue($result['nextPage']);
  1008. $this->assertFalse($result['prevPage']);
  1009. }
  1010. /**
  1011. * test paginate() and custom finders to ensure the count + find
  1012. * use the custom type.
  1013. *
  1014. * @return void
  1015. */
  1016. public function testPaginateCustomFindCount()
  1017. {
  1018. $settings = [
  1019. 'finder' => 'published',
  1020. 'limit' => 2
  1021. ];
  1022. $table = $this->_getMockPosts(['query']);
  1023. $query = $this->_getMockFindQuery();
  1024. $table->expects($this->once())
  1025. ->method('query')
  1026. ->will($this->returnValue($query));
  1027. $query->expects($this->once())->method('applyOptions')
  1028. ->with([
  1029. 'limit' => 2,
  1030. 'page' => 1,
  1031. 'order' => [],
  1032. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1033. 'scope' => null,
  1034. ]);
  1035. $this->Paginator->paginate($table, $settings);
  1036. }
  1037. /**
  1038. * Tests that it is possible to pass an already made query object to
  1039. * paginate()
  1040. *
  1041. * @return void
  1042. */
  1043. public function testPaginateQuery()
  1044. {
  1045. $this->request->query = ['page' => '-1'];
  1046. $settings = [
  1047. 'PaginatorPosts' => [
  1048. 'contain' => ['PaginatorAuthor'],
  1049. 'maxLimit' => 10,
  1050. 'group' => 'PaginatorPosts.published',
  1051. 'order' => ['PaginatorPosts.id' => 'ASC']
  1052. ]
  1053. ];
  1054. $table = $this->_getMockPosts(['find']);
  1055. $query = $this->_getMockFindQuery($table);
  1056. $table->expects($this->never())->method('find');
  1057. $query->expects($this->once())
  1058. ->method('applyOptions')
  1059. ->with([
  1060. 'contain' => ['PaginatorAuthor'],
  1061. 'group' => 'PaginatorPosts.published',
  1062. 'limit' => 10,
  1063. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1064. 'page' => 1,
  1065. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1066. 'scope' => null,
  1067. ]);
  1068. $this->Paginator->paginate($query, $settings);
  1069. }
  1070. /**
  1071. * test paginate() with bind()
  1072. *
  1073. * @return void
  1074. */
  1075. public function testPaginateQueryWithBindValue()
  1076. {
  1077. $config = ConnectionManager::config('test');
  1078. $this->skipIf(strpos($config['driver'], 'Sqlserver') !== false, 'Test temporarily broken in SQLServer');
  1079. $this->loadFixtures('Posts');
  1080. $table = TableRegistry::get('PaginatorPosts');
  1081. $query = $table->find()
  1082. ->where(['PaginatorPosts.author_id BETWEEN :start AND :end'])
  1083. ->bind(':start', 1)
  1084. ->bind(':end', 2);
  1085. $results = $this->Paginator->paginate($query, []);
  1086. $result = $results->toArray();
  1087. $this->assertCount(2, $result);
  1088. $this->assertEquals('First Post', $result[0]->title);
  1089. $this->assertEquals('Third Post', $result[1]->title);
  1090. }
  1091. /**
  1092. * Tests that passing a query object with a limit clause set will
  1093. * overwrite it with the passed defaults.
  1094. *
  1095. * @return void
  1096. */
  1097. public function testPaginateQueryWithLimit()
  1098. {
  1099. $this->request->query = ['page' => '-1'];
  1100. $settings = [
  1101. 'PaginatorPosts' => [
  1102. 'contain' => ['PaginatorAuthor'],
  1103. 'maxLimit' => 10,
  1104. 'limit' => 5,
  1105. 'group' => 'PaginatorPosts.published',
  1106. 'order' => ['PaginatorPosts.id' => 'ASC']
  1107. ]
  1108. ];
  1109. $table = $this->_getMockPosts(['find']);
  1110. $query = $this->_getMockFindQuery($table);
  1111. $query->limit(2);
  1112. $table->expects($this->never())->method('find');
  1113. $query->expects($this->once())
  1114. ->method('applyOptions')
  1115. ->with([
  1116. 'contain' => ['PaginatorAuthor'],
  1117. 'group' => 'PaginatorPosts.published',
  1118. 'limit' => 5,
  1119. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1120. 'page' => 1,
  1121. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1122. 'scope' => null,
  1123. ]);
  1124. $this->Paginator->paginate($query, $settings);
  1125. }
  1126. /**
  1127. * Helper method for making mocks.
  1128. *
  1129. * @param array $methods
  1130. * @return \Cake\ORM\Table
  1131. */
  1132. protected function _getMockPosts($methods = [])
  1133. {
  1134. return $this->getMockBuilder('TestApp\Model\Table\PaginatorPostsTable')
  1135. ->setMethods($methods)
  1136. ->setConstructorArgs([[
  1137. 'connection' => ConnectionManager::get('test'),
  1138. 'alias' => 'PaginatorPosts',
  1139. 'schema' => [
  1140. 'id' => ['type' => 'integer'],
  1141. 'author_id' => ['type' => 'integer', 'null' => false],
  1142. 'title' => ['type' => 'string', 'null' => false],
  1143. 'body' => 'text',
  1144. 'published' => ['type' => 'string', 'length' => 1, 'default' => 'N'],
  1145. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  1146. ]
  1147. ]])
  1148. ->getMock();
  1149. }
  1150. /**
  1151. * Helper method for mocking queries.
  1152. *
  1153. * @return \Cake\ORM\Query
  1154. */
  1155. protected function _getMockFindQuery($table = null)
  1156. {
  1157. $query = $this->getMockBuilder('Cake\ORM\Query')
  1158. ->setMethods(['total', 'all', 'count', 'applyOptions'])
  1159. ->disableOriginalConstructor()
  1160. ->getMock();
  1161. $results = $this->getMockBuilder('Cake\ORM\ResultSet')
  1162. ->disableOriginalConstructor()
  1163. ->getMock();
  1164. $query->expects($this->any())
  1165. ->method('count')
  1166. ->will($this->returnValue(2));
  1167. $query->expects($this->any())
  1168. ->method('all')
  1169. ->will($this->returnValue($results));
  1170. $query->expects($this->any())
  1171. ->method('count')
  1172. ->will($this->returnValue(2));
  1173. $query->repository($table);
  1174. return $query;
  1175. }
  1176. }