PaginatorTest.php 40 KB

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