PaginatorTest.php 39 KB

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