PaginatorTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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 3.5.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Datasource;
  16. use Cake\Core\Configure;
  17. use Cake\Datasource\ConnectionManager;
  18. use Cake\Datasource\EntityInterface;
  19. use Cake\Datasource\Exception\PageOutOfBoundsException;
  20. use Cake\Datasource\Paginator;
  21. use Cake\ORM\Entity;
  22. use Cake\ORM\TableRegistry;
  23. use Cake\TestSuite\TestCase;
  24. class PaginatorTest extends TestCase
  25. {
  26. /**
  27. * fixtures property
  28. *
  29. * @var array
  30. */
  31. public $fixtures = [
  32. 'core.posts', 'core.articles', 'core.articles_tags',
  33. 'core.authors', 'core.authors_tags', 'core.tags'
  34. ];
  35. /**
  36. * Don't load data for fixtures for all tests
  37. *
  38. * @var bool
  39. */
  40. public $autoFixtures = false;
  41. /**
  42. * setup
  43. *
  44. * @return void
  45. */
  46. public function setUp()
  47. {
  48. parent::setUp();
  49. Configure::write('App.namespace', 'TestApp');
  50. $this->Paginator = new Paginator();
  51. $this->Post = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')
  52. ->disableOriginalConstructor()
  53. ->getMock();
  54. }
  55. /**
  56. * tearDown
  57. *
  58. * @return void
  59. */
  60. public function tearDown()
  61. {
  62. parent::tearDown();
  63. TableRegistry::clear();
  64. }
  65. /**
  66. * Test that non-numeric values are rejected for page, and limit
  67. *
  68. * @return void
  69. */
  70. public function testPageParamCasting()
  71. {
  72. $this->Post->expects($this->any())
  73. ->method('alias')
  74. ->will($this->returnValue('Posts'));
  75. $query = $this->_getMockFindQuery();
  76. $this->Post->expects($this->any())
  77. ->method('find')
  78. ->will($this->returnValue($query));
  79. $params = ['page' => '1 " onclick="alert(\'xss\');">'];
  80. $settings = ['limit' => 1, 'maxLimit' => 10];
  81. $this->Paginator->paginate($this->Post, $params, $settings);
  82. $pagingParams = $this->Paginator->getPagingParams();
  83. $this->assertSame(1, $pagingParams['Posts']['page'], 'XSS exploit opened');
  84. }
  85. /**
  86. * test that unknown keys in the default settings are
  87. * passed to the find operations.
  88. *
  89. * @return void
  90. */
  91. public function testPaginateExtraParams()
  92. {
  93. $params = ['page' => '-1'];
  94. $settings = [
  95. 'PaginatorPosts' => [
  96. 'contain' => ['PaginatorAuthor'],
  97. 'maxLimit' => 10,
  98. 'group' => 'PaginatorPosts.published',
  99. 'order' => ['PaginatorPosts.id' => 'ASC']
  100. ],
  101. ];
  102. $table = $this->_getMockPosts(['query']);
  103. $query = $this->_getMockFindQuery();
  104. $table->expects($this->once())
  105. ->method('query')
  106. ->will($this->returnValue($query));
  107. $query->expects($this->once())
  108. ->method('applyOptions')
  109. ->with([
  110. 'contain' => ['PaginatorAuthor'],
  111. 'group' => 'PaginatorPosts.published',
  112. 'limit' => 10,
  113. 'order' => ['PaginatorPosts.id' => 'ASC'],
  114. 'page' => 1,
  115. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  116. 'scope' => null,
  117. ]);
  118. $this->Paginator->paginate($table, $params, $settings);
  119. }
  120. /**
  121. * Test to make sure options get sent to custom finder methods via paginate
  122. *
  123. * @return void
  124. */
  125. public function testPaginateCustomFinderOptions()
  126. {
  127. $this->loadFixtures('Posts');
  128. $settings = [
  129. 'PaginatorPosts' => [
  130. 'finder' => ['author' => ['author_id' => 1]]
  131. ]
  132. ];
  133. $table = TableRegistry::get('PaginatorPosts');
  134. $expected = $table
  135. ->find('author', [
  136. 'conditions' => [
  137. 'PaginatorPosts.author_id' => 1
  138. ]
  139. ])
  140. ->count();
  141. $result = $this->Paginator->paginate($table, [], $settings)->count();
  142. $this->assertEquals($expected, $result);
  143. }
  144. /**
  145. * Test that special paginate types are called and that the type param doesn't leak out into defaults or options.
  146. *
  147. * @return void
  148. */
  149. public function testPaginateCustomFinder()
  150. {
  151. $settings = [
  152. 'PaginatorPosts' => [
  153. 'finder' => 'popular',
  154. 'fields' => ['id', 'title'],
  155. 'maxLimit' => 10,
  156. ]
  157. ];
  158. $table = $this->_getMockPosts(['findPopular']);
  159. $query = $this->_getMockFindQuery();
  160. $table->expects($this->any())
  161. ->method('findPopular')
  162. ->will($this->returnValue($query));
  163. $this->Paginator->paginate($table, [], $settings);
  164. $pagingParams = $this->Paginator->getPagingParams();
  165. $this->assertEquals('popular', $pagingParams['PaginatorPosts']['finder']);
  166. }
  167. /**
  168. * Test that nested eager loaders don't trigger invalid SQL errors.
  169. *
  170. * @return void
  171. */
  172. public function testPaginateNestedEagerLoader()
  173. {
  174. $this->loadFixtures('Articles', 'Tags', 'Authors', 'ArticlesTags', 'AuthorsTags');
  175. $articles = TableRegistry::get('Articles');
  176. $articles->belongsToMany('Tags');
  177. $tags = TableRegistry::get('Tags');
  178. $tags->belongsToMany('Authors');
  179. $articles->eventManager()->on('Model.beforeFind', function ($event, $query) {
  180. $query ->matching('Tags', function ($q) {
  181. return $q->matching('Authors', function ($q) {
  182. return $q->where(['Authors.name' => 'larry']);
  183. });
  184. });
  185. });
  186. $results = $this->Paginator->paginate($articles);
  187. $result = $results->first();
  188. $this->assertInstanceOf(EntityInterface::class, $result);
  189. $this->assertInstanceOf(EntityInterface::class, $result->_matchingData['Tags']);
  190. $this->assertInstanceOf(EntityInterface::class, $result->_matchingData['Authors']);
  191. }
  192. /**
  193. * test that flat default pagination parameters work.
  194. *
  195. * @return void
  196. */
  197. public function testDefaultPaginateParams()
  198. {
  199. $settings = [
  200. 'order' => ['PaginatorPosts.id' => 'DESC'],
  201. 'maxLimit' => 10,
  202. ];
  203. $table = $this->_getMockPosts(['query']);
  204. $query = $this->_getMockFindQuery();
  205. $table->expects($this->once())
  206. ->method('query')
  207. ->will($this->returnValue($query));
  208. $query->expects($this->once())
  209. ->method('applyOptions')
  210. ->with([
  211. 'limit' => 10,
  212. 'page' => 1,
  213. 'order' => ['PaginatorPosts.id' => 'DESC'],
  214. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  215. 'scope' => null,
  216. ]);
  217. $this->Paginator->paginate($table, [], $settings);
  218. }
  219. /**
  220. * test that default sort and default direction are injected into request
  221. *
  222. * @return void
  223. */
  224. public function testDefaultPaginateParamsIntoRequest()
  225. {
  226. $settings = [
  227. 'order' => ['PaginatorPosts.id' => 'DESC'],
  228. 'maxLimit' => 10,
  229. ];
  230. $table = $this->_getMockPosts(['query']);
  231. $query = $this->_getMockFindQuery();
  232. $table->expects($this->once())
  233. ->method('query')
  234. ->will($this->returnValue($query));
  235. $query->expects($this->once())
  236. ->method('applyOptions')
  237. ->with([
  238. 'limit' => 10,
  239. 'page' => 1,
  240. 'order' => ['PaginatorPosts.id' => 'DESC'],
  241. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  242. 'scope' => null,
  243. ]);
  244. $this->Paginator->paginate($table, [], $settings);
  245. $pagingParams = $this->Paginator->getPagingParams();
  246. $this->assertEquals('PaginatorPosts.id', $pagingParams['PaginatorPosts']['sortDefault']);
  247. $this->assertEquals('DESC', $pagingParams['PaginatorPosts']['directionDefault']);
  248. }
  249. /**
  250. * test that option merging prefers specific models
  251. *
  252. * @return void
  253. */
  254. public function testMergeOptionsModelSpecific()
  255. {
  256. $settings = [
  257. 'page' => 1,
  258. 'limit' => 20,
  259. 'maxLimit' => 100,
  260. 'Posts' => [
  261. 'page' => 1,
  262. 'limit' => 10,
  263. 'maxLimit' => 50,
  264. ],
  265. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  266. ];
  267. $defaults = $this->Paginator->getDefaults('Silly', $settings);
  268. $result = $this->Paginator->mergeOptions([], $defaults);
  269. $this->assertEquals($settings, $result);
  270. $defaults = $this->Paginator->getDefaults('Posts', $settings);
  271. $result = $this->Paginator->mergeOptions([], $defaults);
  272. $expected = ['page' => 1, 'limit' => 10, 'maxLimit' => 50, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  273. $this->assertEquals($expected, $result);
  274. }
  275. /**
  276. * test mergeOptions with custom scope
  277. *
  278. * @return void
  279. */
  280. public function testMergeOptionsCustomScope()
  281. {
  282. $params = [
  283. 'page' => 10,
  284. 'limit' => 10,
  285. 'scope' => [
  286. 'page' => 2,
  287. 'limit' => 5,
  288. ]
  289. ];
  290. $settings = [
  291. 'page' => 1,
  292. 'limit' => 20,
  293. 'maxLimit' => 100,
  294. 'finder' => 'myCustomFind',
  295. ];
  296. $defaults = $this->Paginator->getDefaults('Post', $settings);
  297. $result = $this->Paginator->mergeOptions($params, $defaults);
  298. $expected = [
  299. 'page' => 10,
  300. 'limit' => 10,
  301. 'maxLimit' => 100,
  302. 'finder' => 'myCustomFind',
  303. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  304. ];
  305. $this->assertEquals($expected, $result);
  306. $settings = [
  307. 'page' => 1,
  308. 'limit' => 20,
  309. 'maxLimit' => 100,
  310. 'finder' => 'myCustomFind',
  311. 'scope' => 'non-existent',
  312. ];
  313. $defaults = $this->Paginator->getDefaults('Post', $settings);
  314. $result = $this->Paginator->mergeOptions($params, $defaults);
  315. $expected = [
  316. 'page' => 1,
  317. 'limit' => 20,
  318. 'maxLimit' => 100,
  319. 'finder' => 'myCustomFind',
  320. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  321. 'scope' => 'non-existent',
  322. ];
  323. $this->assertEquals($expected, $result);
  324. $settings = [
  325. 'page' => 1,
  326. 'limit' => 20,
  327. 'maxLimit' => 100,
  328. 'finder' => 'myCustomFind',
  329. 'scope' => 'scope',
  330. ];
  331. $defaults = $this->Paginator->getDefaults('Post', $settings);
  332. $result = $this->Paginator->mergeOptions($params, $defaults);
  333. $expected = [
  334. 'page' => 2,
  335. 'limit' => 5,
  336. 'maxLimit' => 100,
  337. 'finder' => 'myCustomFind',
  338. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  339. 'scope' => 'scope',
  340. ];
  341. $this->assertEquals($expected, $result);
  342. }
  343. /**
  344. * test mergeOptions with customFind key
  345. *
  346. * @return void
  347. */
  348. public function testMergeOptionsCustomFindKey()
  349. {
  350. $params = [
  351. 'page' => 10,
  352. 'limit' => 10
  353. ];
  354. $settings = [
  355. 'page' => 1,
  356. 'limit' => 20,
  357. 'maxLimit' => 100,
  358. 'finder' => 'myCustomFind'
  359. ];
  360. $defaults = $this->Paginator->getDefaults('Post', $settings);
  361. $result = $this->Paginator->mergeOptions($params, $defaults);
  362. $expected = [
  363. 'page' => 10,
  364. 'limit' => 10,
  365. 'maxLimit' => 100,
  366. 'finder' => 'myCustomFind',
  367. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  368. ];
  369. $this->assertEquals($expected, $result);
  370. }
  371. /**
  372. * test merging options from the querystring.
  373. *
  374. * @return void
  375. */
  376. public function testMergeOptionsQueryString()
  377. {
  378. $params = [
  379. 'page' => 99,
  380. 'limit' => 75
  381. ];
  382. $settings = [
  383. 'page' => 1,
  384. 'limit' => 20,
  385. 'maxLimit' => 100,
  386. ];
  387. $defaults = $this->Paginator->getDefaults('Post', $settings);
  388. $result = $this->Paginator->mergeOptions($params, $defaults);
  389. $expected = ['page' => 99, 'limit' => 75, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  390. $this->assertEquals($expected, $result);
  391. }
  392. /**
  393. * test that the default whitelist doesn't let people screw with things they should not be allowed to.
  394. *
  395. * @return void
  396. */
  397. public function testMergeOptionsDefaultWhiteList()
  398. {
  399. $params = [
  400. 'page' => 10,
  401. 'limit' => 10,
  402. 'fields' => ['bad.stuff'],
  403. 'recursive' => 1000,
  404. 'conditions' => ['bad.stuff'],
  405. 'contain' => ['bad']
  406. ];
  407. $settings = [
  408. 'page' => 1,
  409. 'limit' => 20,
  410. 'maxLimit' => 100,
  411. ];
  412. $defaults = $this->Paginator->getDefaults('Post', $settings);
  413. $result = $this->Paginator->mergeOptions($params, $defaults);
  414. $expected = ['page' => 10, 'limit' => 10, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  415. $this->assertEquals($expected, $result);
  416. }
  417. /**
  418. * test that modifying the whitelist works.
  419. *
  420. * @return void
  421. */
  422. public function testMergeOptionsExtraWhitelist()
  423. {
  424. $params = [
  425. 'page' => 10,
  426. 'limit' => 10,
  427. 'fields' => ['bad.stuff'],
  428. 'recursive' => 1000,
  429. 'conditions' => ['bad.stuff'],
  430. 'contain' => ['bad']
  431. ];
  432. $settings = [
  433. 'page' => 1,
  434. 'limit' => 20,
  435. 'maxLimit' => 100,
  436. ];
  437. $this->Paginator->config('whitelist', ['fields']);
  438. $defaults = $this->Paginator->getDefaults('Post', $settings);
  439. $result = $this->Paginator->mergeOptions($params, $defaults);
  440. $expected = [
  441. 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'fields' => ['bad.stuff'], 'whitelist' => ['limit', 'sort', 'page', 'direction', 'fields']
  442. ];
  443. $this->assertEquals($expected, $result);
  444. }
  445. /**
  446. * test mergeOptions with limit > maxLimit in code.
  447. *
  448. * @return void
  449. */
  450. public function testMergeOptionsMaxLimit()
  451. {
  452. $settings = [
  453. 'limit' => 200,
  454. 'paramType' => 'named',
  455. ];
  456. $defaults = $this->Paginator->getDefaults('Post', $settings);
  457. $result = $this->Paginator->mergeOptions([], $defaults);
  458. $expected = [
  459. 'page' => 1,
  460. 'limit' => 100,
  461. 'maxLimit' => 100,
  462. 'paramType' => 'named',
  463. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  464. ];
  465. $this->assertEquals($expected, $result);
  466. $settings = [
  467. 'maxLimit' => 10,
  468. 'paramType' => 'named',
  469. ];
  470. $defaults = $this->Paginator->getDefaults('Post', $settings);
  471. $result = $this->Paginator->mergeOptions([], $defaults);
  472. $expected = [
  473. 'page' => 1,
  474. 'limit' => 10,
  475. 'maxLimit' => 10,
  476. 'paramType' => 'named',
  477. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  478. ];
  479. $this->assertEquals($expected, $result);
  480. }
  481. /**
  482. * test getDefaults with limit > maxLimit in code.
  483. *
  484. * @return void
  485. */
  486. public function testGetDefaultMaxLimit()
  487. {
  488. $settings = [
  489. 'page' => 1,
  490. 'limit' => 2,
  491. 'maxLimit' => 10,
  492. 'order' => [
  493. 'Users.username' => 'asc'
  494. ],
  495. ];
  496. $defaults = $this->Paginator->getDefaults('Post', $settings);
  497. $result = $this->Paginator->mergeOptions([], $defaults);
  498. $expected = [
  499. 'page' => 1,
  500. 'limit' => 2,
  501. 'maxLimit' => 10,
  502. 'order' => [
  503. 'Users.username' => 'asc'
  504. ],
  505. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  506. ];
  507. $this->assertEquals($expected, $result);
  508. $settings = [
  509. 'page' => 1,
  510. 'limit' => 100,
  511. 'maxLimit' => 10,
  512. 'order' => [
  513. 'Users.username' => 'asc'
  514. ],
  515. ];
  516. $defaults = $this->Paginator->getDefaults('Post', $settings);
  517. $result = $this->Paginator->mergeOptions([], $defaults);
  518. $expected = [
  519. 'page' => 1,
  520. 'limit' => 10,
  521. 'maxLimit' => 10,
  522. 'order' => [
  523. 'Users.username' => 'asc'
  524. ],
  525. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  526. ];
  527. $this->assertEquals($expected, $result);
  528. }
  529. /**
  530. * Integration test to ensure that validateSort is being used by paginate()
  531. *
  532. * @return void
  533. */
  534. public function testValidateSortInvalid()
  535. {
  536. $table = $this->_getMockPosts(['query']);
  537. $query = $this->_getMockFindQuery();
  538. $table->expects($this->once())
  539. ->method('query')
  540. ->will($this->returnValue($query));
  541. $query->expects($this->once())->method('applyOptions')
  542. ->with([
  543. 'limit' => 20,
  544. 'page' => 1,
  545. 'order' => ['PaginatorPosts.id' => 'asc'],
  546. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  547. 'scope' => null,
  548. ]);
  549. $params = [
  550. 'page' => 1,
  551. 'sort' => 'id',
  552. 'direction' => 'herp'
  553. ];
  554. $this->Paginator->paginate($table, $params);
  555. $pagingParams = $this->Paginator->getPagingParams();
  556. $this->assertEquals('PaginatorPosts.id', $pagingParams['PaginatorPosts']['sort']);
  557. $this->assertEquals('asc', $pagingParams['PaginatorPosts']['direction']);
  558. }
  559. /**
  560. * test that invalid directions are ignored.
  561. *
  562. * @return void
  563. */
  564. public function testValidateSortInvalidDirection()
  565. {
  566. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  567. $model->expects($this->any())
  568. ->method('alias')
  569. ->will($this->returnValue('model'));
  570. $model->expects($this->any())
  571. ->method('hasField')
  572. ->will($this->returnValue(true));
  573. $options = ['sort' => 'something', 'direction' => 'boogers'];
  574. $result = $this->Paginator->validateSort($model, $options);
  575. $this->assertEquals('asc', $result['order']['model.something']);
  576. }
  577. /**
  578. * Test that a really large page number gets clamped to the max page size.
  579. *
  580. * @return void
  581. */
  582. public function testOutOfRangePageNumberGetsClamped()
  583. {
  584. $this->loadFixtures('Posts');
  585. $params['page'] = 3000;
  586. $table = TableRegistry::get('PaginatorPosts');
  587. try {
  588. $this->Paginator->paginate($table, $params);
  589. $this->fail('No exception raised');
  590. } catch (PageOutOfBoundsException $e) {
  591. $pagingParams = $this->Paginator->getPagingParams();
  592. $this->assertEquals(
  593. 1,
  594. $pagingParams['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\Datasource\Exception\PageOutOfBoundsException
  603. * @return void
  604. */
  605. public function testOutOfVeryBigPageNumberGetsClamped()
  606. {
  607. $this->loadFixtures('Posts');
  608. $params = [
  609. 'page' => '3000000000000000000000000',
  610. ];
  611. $table = TableRegistry::get('PaginatorPosts');
  612. $this->Paginator->paginate($table, $params);
  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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->getMock();
  773. $model->expects($this->any())
  774. ->method('alias')
  775. ->will($this->returnValue('model'));
  776. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  777. $options = [
  778. 'order' => '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\Datasource\RepositoryInterface')->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\Datasource\RepositoryInterface')->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. $params = [
  888. 'limit' => '1000'
  889. ];
  890. $this->Paginator->paginate($table, $params, $settings);
  891. $pagingParams = $this->Paginator->getPagingParams();
  892. $this->assertEquals(100, $pagingParams['PaginatorPosts']['limit']);
  893. $this->assertEquals(100, $pagingParams['PaginatorPosts']['perPage']);
  894. $params = [
  895. 'limit' => '10'
  896. ];
  897. $this->Paginator->paginate($table, $params, $settings);
  898. $pagingParams = $this->Paginator->getPagingParams();
  899. $this->assertEquals(10, $pagingParams['PaginatorPosts']['limit']);
  900. $this->assertEquals(10, $pagingParams['PaginatorPosts']['perPage']);
  901. }
  902. /**
  903. * test paginate() and custom find, to make sure the correct count is returned.
  904. *
  905. * @return void
  906. */
  907. public function testPaginateCustomFind()
  908. {
  909. $this->loadFixtures('Posts');
  910. $titleExtractor = function ($result) {
  911. $ids = [];
  912. foreach ($result as $record) {
  913. $ids[] = $record->title;
  914. }
  915. return $ids;
  916. };
  917. $table = TableRegistry::get('PaginatorPosts');
  918. $data = ['author_id' => 3, 'title' => 'Fourth Post', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  919. $result = $table->save(new Entity($data));
  920. $this->assertNotEmpty($result);
  921. $result = $this->Paginator->paginate($table);
  922. $this->assertCount(4, $result, '4 rows should come back');
  923. $this->assertEquals(['First Post', 'Second Post', 'Third Post', 'Fourth Post'], $titleExtractor($result));
  924. $pagingParams = $this->Paginator->getPagingParams();
  925. $this->assertEquals(4, $pagingParams['PaginatorPosts']['current']);
  926. $this->assertEquals(4, $pagingParams['PaginatorPosts']['count']);
  927. $settings = ['finder' => 'published'];
  928. $result = $this->Paginator->paginate($table, [], $settings);
  929. $this->assertCount(3, $result, '3 rows should come back');
  930. $this->assertEquals(['First Post', 'Second Post', 'Third Post'], $titleExtractor($result));
  931. $pagingParams = $this->Paginator->getPagingParams();
  932. $this->assertEquals(3, $pagingParams['PaginatorPosts']['current']);
  933. $this->assertEquals(3, $pagingParams['PaginatorPosts']['count']);
  934. $settings = ['finder' => 'published', 'limit' => 2, 'page' => 2];
  935. $result = $this->Paginator->paginate($table, [], $settings);
  936. $this->assertCount(1, $result, '1 rows should come back');
  937. $this->assertEquals(['Third Post'], $titleExtractor($result));
  938. $pagingParams = $this->Paginator->getPagingParams();
  939. $this->assertEquals(1, $pagingParams['PaginatorPosts']['current']);
  940. $this->assertEquals(3, $pagingParams['PaginatorPosts']['count']);
  941. $this->assertEquals(2, $pagingParams['PaginatorPosts']['pageCount']);
  942. $settings = ['finder' => 'published', 'limit' => 2];
  943. $result = $this->Paginator->paginate($table, [], $settings);
  944. $this->assertCount(2, $result, '2 rows should come back');
  945. $this->assertEquals(['First Post', 'Second Post'], $titleExtractor($result));
  946. $pagingParams = $this->Paginator->getPagingParams();
  947. $this->assertEquals(2, $pagingParams['PaginatorPosts']['current']);
  948. $this->assertEquals(3, $pagingParams['PaginatorPosts']['count']);
  949. $this->assertEquals(2, $pagingParams['PaginatorPosts']['pageCount']);
  950. $this->assertTrue($pagingParams['PaginatorPosts']['nextPage']);
  951. $this->assertFalse($pagingParams['PaginatorPosts']['prevPage']);
  952. $this->assertEquals(2, $pagingParams['PaginatorPosts']['perPage']);
  953. $this->assertNull($pagingParams['PaginatorPosts']['limit']);
  954. }
  955. /**
  956. * test paginate() and custom find with fields array, to make sure the correct count is returned.
  957. *
  958. * @return void
  959. */
  960. public function testPaginateCustomFindFieldsArray()
  961. {
  962. $this->loadFixtures('Posts');
  963. $table = TableRegistry::get('PaginatorPosts');
  964. $data = ['author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  965. $table->save(new Entity($data));
  966. $settings = [
  967. 'finder' => 'list',
  968. 'conditions' => ['PaginatorPosts.published' => 'Y'],
  969. 'limit' => 2
  970. ];
  971. $results = $this->Paginator->paginate($table, [], $settings);
  972. $result = $results->toArray();
  973. $expected = [
  974. 1 => 'First Post',
  975. 2 => 'Second Post',
  976. ];
  977. $this->assertEquals($expected, $result);
  978. $result = $this->Paginator->getPagingParams()['PaginatorPosts'];
  979. $this->assertEquals(2, $result['current']);
  980. $this->assertEquals(3, $result['count']);
  981. $this->assertEquals(2, $result['pageCount']);
  982. $this->assertTrue($result['nextPage']);
  983. $this->assertFalse($result['prevPage']);
  984. }
  985. /**
  986. * test paginate() and custom finders to ensure the count + find
  987. * use the custom type.
  988. *
  989. * @return void
  990. */
  991. public function testPaginateCustomFindCount()
  992. {
  993. $settings = [
  994. 'finder' => 'published',
  995. 'limit' => 2
  996. ];
  997. $table = $this->_getMockPosts(['query']);
  998. $query = $this->_getMockFindQuery();
  999. $table->expects($this->once())
  1000. ->method('query')
  1001. ->will($this->returnValue($query));
  1002. $query->expects($this->once())->method('applyOptions')
  1003. ->with([
  1004. 'limit' => 2,
  1005. 'page' => 1,
  1006. 'order' => [],
  1007. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1008. 'scope' => null,
  1009. ]);
  1010. $this->Paginator->paginate($table, [], $settings);
  1011. }
  1012. /**
  1013. * Tests that it is possible to pass an already made query object to
  1014. * paginate()
  1015. *
  1016. * @return void
  1017. */
  1018. public function testPaginateQuery()
  1019. {
  1020. $params = ['page' => '-1'];
  1021. $settings = [
  1022. 'PaginatorPosts' => [
  1023. 'contain' => ['PaginatorAuthor'],
  1024. 'maxLimit' => 10,
  1025. 'group' => 'PaginatorPosts.published',
  1026. 'order' => ['PaginatorPosts.id' => 'ASC']
  1027. ]
  1028. ];
  1029. $table = $this->_getMockPosts(['find']);
  1030. $query = $this->_getMockFindQuery($table);
  1031. $table->expects($this->never())->method('find');
  1032. $query->expects($this->once())
  1033. ->method('applyOptions')
  1034. ->with([
  1035. 'contain' => ['PaginatorAuthor'],
  1036. 'group' => 'PaginatorPosts.published',
  1037. 'limit' => 10,
  1038. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1039. 'page' => 1,
  1040. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1041. 'scope' => null,
  1042. ]);
  1043. $this->Paginator->paginate($query, $params, $settings);
  1044. }
  1045. /**
  1046. * test paginate() with bind()
  1047. *
  1048. * @return void
  1049. */
  1050. public function testPaginateQueryWithBindValue()
  1051. {
  1052. $config = ConnectionManager::config('test');
  1053. $this->skipIf(strpos($config['driver'], 'Sqlserver') !== false, 'Test temporarily broken in SQLServer');
  1054. $this->loadFixtures('Posts');
  1055. $table = TableRegistry::get('PaginatorPosts');
  1056. $query = $table->find()
  1057. ->where(['PaginatorPosts.author_id BETWEEN :start AND :end'])
  1058. ->bind(':start', 1)
  1059. ->bind(':end', 2);
  1060. $results = $this->Paginator->paginate($query, []);
  1061. $result = $results->toArray();
  1062. $this->assertCount(2, $result);
  1063. $this->assertEquals('First Post', $result[0]->title);
  1064. $this->assertEquals('Third Post', $result[1]->title);
  1065. }
  1066. /**
  1067. * Tests that passing a query object with a limit clause set will
  1068. * overwrite it with the passed defaults.
  1069. *
  1070. * @return void
  1071. */
  1072. public function testPaginateQueryWithLimit()
  1073. {
  1074. $params = ['page' => '-1'];
  1075. $settings = [
  1076. 'PaginatorPosts' => [
  1077. 'contain' => ['PaginatorAuthor'],
  1078. 'maxLimit' => 10,
  1079. 'limit' => 5,
  1080. 'group' => 'PaginatorPosts.published',
  1081. 'order' => ['PaginatorPosts.id' => 'ASC']
  1082. ]
  1083. ];
  1084. $table = $this->_getMockPosts(['find']);
  1085. $query = $this->_getMockFindQuery($table);
  1086. $query->limit(2);
  1087. $table->expects($this->never())->method('find');
  1088. $query->expects($this->once())
  1089. ->method('applyOptions')
  1090. ->with([
  1091. 'contain' => ['PaginatorAuthor'],
  1092. 'group' => 'PaginatorPosts.published',
  1093. 'limit' => 5,
  1094. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1095. 'page' => 1,
  1096. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1097. 'scope' => null,
  1098. ]);
  1099. $this->Paginator->paginate($query, $params, $settings);
  1100. }
  1101. /**
  1102. * Helper method for making mocks.
  1103. *
  1104. * @param array $methods
  1105. * @return \Cake\ORM\Table
  1106. */
  1107. protected function _getMockPosts($methods = [])
  1108. {
  1109. return $this->getMockBuilder('TestApp\Model\Table\PaginatorPostsTable')
  1110. ->setMethods($methods)
  1111. ->setConstructorArgs([[
  1112. 'connection' => ConnectionManager::get('test'),
  1113. 'alias' => 'PaginatorPosts',
  1114. 'schema' => [
  1115. 'id' => ['type' => 'integer'],
  1116. 'author_id' => ['type' => 'integer', 'null' => false],
  1117. 'title' => ['type' => 'string', 'null' => false],
  1118. 'body' => 'text',
  1119. 'published' => ['type' => 'string', 'length' => 1, 'default' => 'N'],
  1120. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  1121. ]
  1122. ]])
  1123. ->getMock();
  1124. }
  1125. /**
  1126. * Helper method for mocking queries.
  1127. *
  1128. * @return \Cake\ORM\Query
  1129. */
  1130. protected function _getMockFindQuery($table = null)
  1131. {
  1132. $query = $this->getMockBuilder('Cake\ORM\Query')
  1133. ->setMethods(['total', 'all', 'count', 'applyOptions'])
  1134. ->disableOriginalConstructor()
  1135. ->getMock();
  1136. $results = $this->getMockBuilder('Cake\ORM\ResultSet')
  1137. ->disableOriginalConstructor()
  1138. ->getMock();
  1139. $query->expects($this->any())
  1140. ->method('count')
  1141. ->will($this->returnValue(2));
  1142. $query->expects($this->any())
  1143. ->method('all')
  1144. ->will($this->returnValue($results));
  1145. $query->expects($this->any())
  1146. ->method('count')
  1147. ->will($this->returnValue(2));
  1148. $query->repository($table);
  1149. return $query;
  1150. }
  1151. }