PaginatorComponentTest.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\ComponentRegistry;
  17. use Cake\Controller\Component\PaginatorComponent;
  18. use Cake\Controller\Controller;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\Datasource\EntityInterface;
  21. use Cake\Datasource\Paginator;
  22. use Cake\Http\ServerRequest;
  23. use Cake\Network\Exception\NotFoundException;
  24. use Cake\ORM\Entity;
  25. use Cake\ORM\TableRegistry;
  26. use Cake\TestSuite\TestCase;
  27. use stdClass;
  28. /**
  29. * PaginatorTestController class
  30. */
  31. class PaginatorTestController extends Controller
  32. {
  33. /**
  34. * components property
  35. *
  36. * @var array
  37. */
  38. public $components = ['Paginator'];
  39. }
  40. /**
  41. * Custom paginator
  42. */
  43. class CustomPaginator extends Paginator
  44. {
  45. }
  46. class PaginatorComponentTest extends TestCase
  47. {
  48. /**
  49. * fixtures property
  50. *
  51. * @var array
  52. */
  53. public $fixtures = [
  54. 'core.posts', 'core.articles', 'core.articles_tags',
  55. 'core.authors', 'core.authors_tags', 'core.tags'
  56. ];
  57. /**
  58. * Don't load data for fixtures for all tests
  59. *
  60. * @var bool
  61. */
  62. public $autoFixtures = false;
  63. /**
  64. * setup
  65. *
  66. * @return void
  67. */
  68. public function setUp()
  69. {
  70. parent::setUp();
  71. static::setAppNamespace();
  72. $this->request = new ServerRequest('controller_posts/index');
  73. $this->request->params['pass'] = [];
  74. $controller = new Controller($this->request);
  75. $this->registry = new ComponentRegistry($controller);
  76. $this->Paginator = new PaginatorComponent($this->registry, []);
  77. $this->Post = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')
  78. ->disableOriginalConstructor()
  79. ->getMock();
  80. }
  81. /**
  82. * tearDown
  83. *
  84. * @return void
  85. */
  86. public function tearDown()
  87. {
  88. parent::tearDown();
  89. TableRegistry::clear();
  90. }
  91. /**
  92. * testPaginatorSetting
  93. *
  94. * @return void
  95. */
  96. public function testPaginatorSetting()
  97. {
  98. $paginator = new CustomPaginator();
  99. $component = new PaginatorComponent($this->registry, [
  100. 'paginator' => $paginator
  101. ]);
  102. $this->assertSame($paginator, $component->getPaginator());
  103. $component = new PaginatorComponent($this->registry, []);
  104. $this->assertNotSame($paginator, $component->getPaginator());
  105. $component->setPaginator($paginator);
  106. $this->assertSame($paginator, $component->getPaginator());
  107. }
  108. /**
  109. * Test that an exception is thrown when paginator option is invalid.
  110. *
  111. * @return void
  112. */
  113. public function testInvalidPaginatorOption()
  114. {
  115. $this->expectException(\InvalidArgumentException::class);
  116. $this->expectExceptionMessage('Paginator must be an instance of Cake\Datasource\Paginator');
  117. new PaginatorComponent($this->registry, [
  118. 'paginator' => new stdClass()
  119. ]);
  120. }
  121. /**
  122. * Test that non-numeric values are rejected for page, and limit
  123. *
  124. * @return void
  125. */
  126. public function testPageParamCasting()
  127. {
  128. $this->Post->expects($this->any())
  129. ->method('alias')
  130. ->will($this->returnValue('Posts'));
  131. $query = $this->_getMockFindQuery();
  132. $this->Post->expects($this->any())
  133. ->method('find')
  134. ->will($this->returnValue($query));
  135. $this->request->query = ['page' => '1 " onclick="alert(\'xss\');">'];
  136. $settings = ['limit' => 1, 'maxLimit' => 10];
  137. $this->Paginator->paginate($this->Post, $settings);
  138. $this->assertSame(1, $this->request->params['paging']['Posts']['page'], 'XSS exploit opened');
  139. }
  140. /**
  141. * test that unknown keys in the default settings are
  142. * passed to the find operations.
  143. *
  144. * @return void
  145. */
  146. public function testPaginateExtraParams()
  147. {
  148. $this->request->query = ['page' => '-1'];
  149. $settings = [
  150. 'PaginatorPosts' => [
  151. 'contain' => ['PaginatorAuthor'],
  152. 'maxLimit' => 10,
  153. 'group' => 'PaginatorPosts.published',
  154. 'order' => ['PaginatorPosts.id' => 'ASC']
  155. ],
  156. ];
  157. $table = $this->_getMockPosts(['query']);
  158. $query = $this->_getMockFindQuery();
  159. $table->expects($this->once())
  160. ->method('query')
  161. ->will($this->returnValue($query));
  162. $query->expects($this->once())
  163. ->method('applyOptions')
  164. ->with([
  165. 'contain' => ['PaginatorAuthor'],
  166. 'group' => 'PaginatorPosts.published',
  167. 'limit' => 10,
  168. 'order' => ['PaginatorPosts.id' => 'ASC'],
  169. 'page' => 1,
  170. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  171. 'scope' => null,
  172. ]);
  173. $this->Paginator->paginate($table, $settings);
  174. }
  175. /**
  176. * Test to make sure options get sent to custom finder methods via paginate
  177. *
  178. * @return void
  179. */
  180. public function testPaginateCustomFinderOptions()
  181. {
  182. $this->loadFixtures('Posts');
  183. $settings = [
  184. 'PaginatorPosts' => [
  185. 'finder' => ['author' => ['author_id' => 1]]
  186. ]
  187. ];
  188. $table = TableRegistry::get('PaginatorPosts');
  189. $expected = $table
  190. ->find('author', [
  191. 'conditions' => [
  192. 'PaginatorPosts.author_id' => 1
  193. ]
  194. ])
  195. ->count();
  196. $result = $this->Paginator->paginate($table, $settings)->count();
  197. $this->assertEquals($expected, $result);
  198. }
  199. /**
  200. * testRequestParamsSetting
  201. *
  202. * @return void
  203. * @see https://github.com/cakephp/cakephp/issues/11655
  204. */
  205. public function testRequestParamsSetting()
  206. {
  207. $this->loadFixtures('Posts');
  208. $settings = [
  209. 'PaginatorPosts' => [
  210. 'limit' => 10,
  211. ]
  212. ];
  213. $table = TableRegistry::get('PaginatorPosts');
  214. $this->Paginator->paginate($table, $settings);
  215. $this->assertArrayHasKey('PaginatorPosts', $this->request->params['paging']);
  216. $this->assertArrayNotHasKey(0, $this->request->params['paging']);
  217. }
  218. /**
  219. * Test that special paginate types are called and that the type param doesn't leak out into defaults or options.
  220. *
  221. * @return void
  222. */
  223. public function testPaginateCustomFinder()
  224. {
  225. $settings = [
  226. 'PaginatorPosts' => [
  227. 'finder' => 'popular',
  228. 'fields' => ['id', 'title'],
  229. 'maxLimit' => 10,
  230. ]
  231. ];
  232. $table = $this->_getMockPosts(['findPopular']);
  233. $query = $this->_getMockFindQuery();
  234. $table->expects($this->any())
  235. ->method('findPopular')
  236. ->will($this->returnValue($query));
  237. $this->Paginator->paginate($table, $settings);
  238. $this->assertEquals('popular', $this->request->params['paging']['PaginatorPosts']['finder']);
  239. }
  240. /**
  241. * Test that nested eager loaders don't trigger invalid SQL errors.
  242. *
  243. * @return void
  244. */
  245. public function testPaginateNestedEagerLoader()
  246. {
  247. $this->loadFixtures('Articles', 'Tags', 'Authors', 'ArticlesTags', 'AuthorsTags');
  248. $articles = TableRegistry::get('Articles');
  249. $articles->belongsToMany('Tags');
  250. $tags = TableRegistry::get('Tags');
  251. $tags->belongsToMany('Authors');
  252. $articles->eventManager()->on('Model.beforeFind', function ($event, $query) {
  253. $query ->matching('Tags', function ($q) {
  254. return $q->matching('Authors', function ($q) {
  255. return $q->where(['Authors.name' => 'larry']);
  256. });
  257. });
  258. });
  259. $results = $this->Paginator->paginate($articles, []);
  260. $result = $results->first();
  261. $this->assertInstanceOf(EntityInterface::class, $result);
  262. $this->assertInstanceOf(EntityInterface::class, $result->_matchingData['Tags']);
  263. $this->assertInstanceOf(EntityInterface::class, $result->_matchingData['Authors']);
  264. }
  265. /**
  266. * test that flat default pagination parameters work.
  267. *
  268. * @return void
  269. */
  270. public function testDefaultPaginateParams()
  271. {
  272. $settings = [
  273. 'order' => ['PaginatorPosts.id' => 'DESC'],
  274. 'maxLimit' => 10,
  275. ];
  276. $table = $this->_getMockPosts(['query']);
  277. $query = $this->_getMockFindQuery();
  278. $table->expects($this->once())
  279. ->method('query')
  280. ->will($this->returnValue($query));
  281. $query->expects($this->once())
  282. ->method('applyOptions')
  283. ->with([
  284. 'limit' => 10,
  285. 'page' => 1,
  286. 'order' => ['PaginatorPosts.id' => 'DESC'],
  287. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  288. 'scope' => null,
  289. ]);
  290. $this->Paginator->paginate($table, $settings);
  291. }
  292. /**
  293. * test that default sort and default direction are injected into request
  294. *
  295. * @return void
  296. */
  297. public function testDefaultPaginateParamsIntoRequest()
  298. {
  299. $settings = [
  300. 'order' => ['PaginatorPosts.id' => 'DESC'],
  301. 'maxLimit' => 10,
  302. ];
  303. $table = $this->_getMockPosts(['query']);
  304. $query = $this->_getMockFindQuery();
  305. $table->expects($this->once())
  306. ->method('query')
  307. ->will($this->returnValue($query));
  308. $query->expects($this->once())
  309. ->method('applyOptions')
  310. ->with([
  311. 'limit' => 10,
  312. 'page' => 1,
  313. 'order' => ['PaginatorPosts.id' => 'DESC'],
  314. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  315. 'scope' => null,
  316. ]);
  317. $this->Paginator->paginate($table, $settings);
  318. $this->assertEquals('PaginatorPosts.id', $this->request->params['paging']['PaginatorPosts']['sortDefault']);
  319. $this->assertEquals('DESC', $this->request->params['paging']['PaginatorPosts']['directionDefault']);
  320. }
  321. /**
  322. * test that option merging prefers specific models
  323. *
  324. * @return void
  325. */
  326. public function testMergeOptionsModelSpecific()
  327. {
  328. $settings = [
  329. 'page' => 1,
  330. 'limit' => 20,
  331. 'maxLimit' => 100,
  332. 'Posts' => [
  333. 'page' => 1,
  334. 'limit' => 10,
  335. 'maxLimit' => 50,
  336. ],
  337. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  338. ];
  339. $result = $this->Paginator->mergeOptions('Silly', $settings);
  340. $this->assertEquals($settings, $result);
  341. $result = $this->Paginator->mergeOptions('Posts', $settings);
  342. $expected = ['page' => 1, 'limit' => 10, 'maxLimit' => 50, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  343. $this->assertEquals($expected, $result);
  344. }
  345. /**
  346. * test mergeOptions with custom scope
  347. *
  348. * @return void
  349. */
  350. public function testMergeOptionsCustomScope()
  351. {
  352. $this->request->query = [
  353. 'page' => 10,
  354. 'limit' => 10,
  355. 'scope' => [
  356. 'page' => 2,
  357. 'limit' => 5,
  358. ]
  359. ];
  360. $settings = [
  361. 'page' => 1,
  362. 'limit' => 20,
  363. 'maxLimit' => 100,
  364. 'finder' => 'myCustomFind',
  365. ];
  366. $result = $this->Paginator->mergeOptions('Post', $settings);
  367. $expected = [
  368. 'page' => 10,
  369. 'limit' => 10,
  370. 'maxLimit' => 100,
  371. 'finder' => 'myCustomFind',
  372. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  373. ];
  374. $this->assertEquals($expected, $result);
  375. $settings = [
  376. 'page' => 1,
  377. 'limit' => 20,
  378. 'maxLimit' => 100,
  379. 'finder' => 'myCustomFind',
  380. 'scope' => 'non-existent',
  381. ];
  382. $result = $this->Paginator->mergeOptions('Post', $settings);
  383. $expected = [
  384. 'page' => 1,
  385. 'limit' => 20,
  386. 'maxLimit' => 100,
  387. 'finder' => 'myCustomFind',
  388. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  389. 'scope' => 'non-existent',
  390. ];
  391. $this->assertEquals($expected, $result);
  392. $settings = [
  393. 'page' => 1,
  394. 'limit' => 20,
  395. 'maxLimit' => 100,
  396. 'finder' => 'myCustomFind',
  397. 'scope' => 'scope',
  398. ];
  399. $result = $this->Paginator->mergeOptions('Post', $settings);
  400. $expected = [
  401. 'page' => 2,
  402. 'limit' => 5,
  403. 'maxLimit' => 100,
  404. 'finder' => 'myCustomFind',
  405. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  406. 'scope' => 'scope',
  407. ];
  408. $this->assertEquals($expected, $result);
  409. }
  410. /**
  411. * test mergeOptions with customFind key
  412. *
  413. * @return void
  414. */
  415. public function testMergeOptionsCustomFindKey()
  416. {
  417. $this->request->query = [
  418. 'page' => 10,
  419. 'limit' => 10
  420. ];
  421. $settings = [
  422. 'page' => 1,
  423. 'limit' => 20,
  424. 'maxLimit' => 100,
  425. 'finder' => 'myCustomFind'
  426. ];
  427. $result = $this->Paginator->mergeOptions('Post', $settings);
  428. $expected = [
  429. 'page' => 10,
  430. 'limit' => 10,
  431. 'maxLimit' => 100,
  432. 'finder' => 'myCustomFind',
  433. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  434. ];
  435. $this->assertEquals($expected, $result);
  436. }
  437. /**
  438. * test merging options from the querystring.
  439. *
  440. * @return void
  441. */
  442. public function testMergeOptionsQueryString()
  443. {
  444. $this->request->query = [
  445. 'page' => 99,
  446. 'limit' => 75
  447. ];
  448. $settings = [
  449. 'page' => 1,
  450. 'limit' => 20,
  451. 'maxLimit' => 100,
  452. ];
  453. $result = $this->Paginator->mergeOptions('Post', $settings);
  454. $expected = ['page' => 99, 'limit' => 75, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  455. $this->assertEquals($expected, $result);
  456. }
  457. /**
  458. * test that the default whitelist doesn't let people screw with things they should not be allowed to.
  459. *
  460. * @return void
  461. */
  462. public function testMergeOptionsDefaultWhiteList()
  463. {
  464. $this->request->query = [
  465. 'page' => 10,
  466. 'limit' => 10,
  467. 'fields' => ['bad.stuff'],
  468. 'recursive' => 1000,
  469. 'conditions' => ['bad.stuff'],
  470. 'contain' => ['bad']
  471. ];
  472. $settings = [
  473. 'page' => 1,
  474. 'limit' => 20,
  475. 'maxLimit' => 100,
  476. ];
  477. $result = $this->Paginator->mergeOptions('Post', $settings);
  478. $expected = ['page' => 10, 'limit' => 10, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction']];
  479. $this->assertEquals($expected, $result);
  480. }
  481. /**
  482. * test that modifying the whitelist works.
  483. *
  484. * @return void
  485. */
  486. public function testMergeOptionsExtraWhitelist()
  487. {
  488. $this->request->query = [
  489. 'page' => 10,
  490. 'limit' => 10,
  491. 'fields' => ['bad.stuff'],
  492. 'recursive' => 1000,
  493. 'conditions' => ['bad.stuff'],
  494. 'contain' => ['bad']
  495. ];
  496. $settings = [
  497. 'page' => 1,
  498. 'limit' => 20,
  499. 'maxLimit' => 100,
  500. ];
  501. $this->Paginator->config('whitelist', ['fields']);
  502. $result = $this->Paginator->mergeOptions('Post', $settings);
  503. $expected = [
  504. 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'fields' => ['bad.stuff'], 'whitelist' => ['limit', 'sort', 'page', 'direction', 'fields']
  505. ];
  506. $this->assertEquals($expected, $result);
  507. }
  508. /**
  509. * test mergeOptions with limit > maxLimit in code.
  510. *
  511. * @return void
  512. */
  513. public function testMergeOptionsMaxLimit()
  514. {
  515. $settings = [
  516. 'limit' => 200,
  517. 'paramType' => 'named',
  518. ];
  519. $result = $this->Paginator->mergeOptions('Post', $settings);
  520. $expected = [
  521. 'page' => 1,
  522. 'limit' => 100,
  523. 'maxLimit' => 100,
  524. 'paramType' => 'named',
  525. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  526. ];
  527. $this->assertEquals($expected, $result);
  528. $settings = [
  529. 'maxLimit' => 10,
  530. 'paramType' => 'named',
  531. ];
  532. $result = $this->Paginator->mergeOptions('Post', $settings);
  533. $expected = [
  534. 'page' => 1,
  535. 'limit' => 10,
  536. 'maxLimit' => 10,
  537. 'paramType' => 'named',
  538. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  539. ];
  540. $this->assertEquals($expected, $result);
  541. }
  542. /**
  543. * test getDefaults with limit > maxLimit in code.
  544. *
  545. * @return void
  546. */
  547. public function testGetDefaultMaxLimit()
  548. {
  549. $settings = [
  550. 'page' => 1,
  551. 'limit' => 2,
  552. 'maxLimit' => 10,
  553. 'order' => [
  554. 'Users.username' => 'asc'
  555. ],
  556. ];
  557. $result = $this->Paginator->mergeOptions('Post', $settings);
  558. $expected = [
  559. 'page' => 1,
  560. 'limit' => 2,
  561. 'maxLimit' => 10,
  562. 'order' => [
  563. 'Users.username' => 'asc'
  564. ],
  565. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  566. ];
  567. $this->assertEquals($expected, $result);
  568. $settings = [
  569. 'page' => 1,
  570. 'limit' => 100,
  571. 'maxLimit' => 10,
  572. 'order' => [
  573. 'Users.username' => 'asc'
  574. ],
  575. ];
  576. $result = $this->Paginator->mergeOptions('Post', $settings);
  577. $expected = [
  578. 'page' => 1,
  579. 'limit' => 10,
  580. 'maxLimit' => 10,
  581. 'order' => [
  582. 'Users.username' => 'asc'
  583. ],
  584. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  585. ];
  586. $this->assertEquals($expected, $result);
  587. }
  588. /**
  589. * Integration test to ensure that validateSort is being used by paginate()
  590. *
  591. * @return void
  592. */
  593. public function testValidateSortInvalid()
  594. {
  595. $table = $this->_getMockPosts(['query']);
  596. $query = $this->_getMockFindQuery();
  597. $table->expects($this->once())
  598. ->method('query')
  599. ->will($this->returnValue($query));
  600. $query->expects($this->once())->method('applyOptions')
  601. ->with([
  602. 'limit' => 20,
  603. 'page' => 1,
  604. 'order' => ['PaginatorPosts.id' => 'asc'],
  605. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  606. 'scope' => null,
  607. ]);
  608. $this->request->query = [
  609. 'page' => 1,
  610. 'sort' => 'id',
  611. 'direction' => 'herp'
  612. ];
  613. $this->Paginator->paginate($table);
  614. $this->assertEquals('PaginatorPosts.id', $this->request->params['paging']['PaginatorPosts']['sort']);
  615. $this->assertEquals('asc', $this->request->params['paging']['PaginatorPosts']['direction']);
  616. }
  617. /**
  618. * test that invalid directions are ignored.
  619. *
  620. * @return void
  621. */
  622. public function testValidateSortInvalidDirection()
  623. {
  624. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  625. $model->expects($this->any())
  626. ->method('alias')
  627. ->will($this->returnValue('model'));
  628. $model->expects($this->any())
  629. ->method('hasField')
  630. ->will($this->returnValue(true));
  631. $options = ['sort' => 'something', 'direction' => 'boogers'];
  632. $result = $this->Paginator->validateSort($model, $options);
  633. $this->assertEquals('asc', $result['order']['model.something']);
  634. }
  635. /**
  636. * Test empty pagination result.
  637. *
  638. * @return void
  639. */
  640. public function testEmptyPaginationResult()
  641. {
  642. $this->loadFixtures('Posts');
  643. $table = TableRegistry::get('PaginatorPosts');
  644. $table->deleteAll('1=1');
  645. $this->Paginator->paginate($table);
  646. $this->assertSame(
  647. 0,
  648. $this->request->params['paging']['PaginatorPosts']['count'],
  649. 'Count should be 0'
  650. );
  651. $this->assertSame(
  652. 1,
  653. $this->request->params['paging']['PaginatorPosts']['page'],
  654. 'Page number should not be 0'
  655. );
  656. $this->assertSame(
  657. 1,
  658. $this->request->params['paging']['PaginatorPosts']['pageCount'],
  659. 'Page count number should not be 0'
  660. );
  661. }
  662. /**
  663. * Test that a really large page number gets clamped to the max page size.
  664. *
  665. * @return void
  666. */
  667. public function testOutOfRangePageNumberGetsClamped()
  668. {
  669. $this->loadFixtures('Posts');
  670. $this->request->query['page'] = 3000;
  671. $table = TableRegistry::get('PaginatorPosts');
  672. try {
  673. $this->Paginator->paginate($table);
  674. $this->fail('No exception raised');
  675. } catch (NotFoundException $e) {
  676. $this->assertEquals(
  677. 1,
  678. $this->request->params['paging']['PaginatorPosts']['page'],
  679. 'Page number should not be 0'
  680. );
  681. }
  682. }
  683. /**
  684. * Test that a out of bounds request still knows about the page size
  685. *
  686. * @return void
  687. */
  688. public function testOutOfRangePageNumberStillProvidesPageCount()
  689. {
  690. $this->loadFixtures('Posts');
  691. $this->request->query['limit'] = 1;
  692. $this->request->query['page'] = 4;
  693. $table = TableRegistry::get('PaginatorPosts');
  694. try {
  695. $this->Paginator->paginate($table);
  696. $this->fail('No exception raised');
  697. } catch (NotFoundException $e) {
  698. $this->assertEquals(
  699. 3,
  700. $this->request->params['paging']['PaginatorPosts']['pageCount'],
  701. 'Page count number should not be 0'
  702. );
  703. }
  704. }
  705. /**
  706. * Test that a really REALLY large page number gets clamped to the max page size.
  707. *
  708. * @return void
  709. */
  710. public function testOutOfVeryBigPageNumberGetsClamped()
  711. {
  712. $this->expectException(\Cake\Network\Exception\NotFoundException::class);
  713. $this->loadFixtures('Posts');
  714. $this->request->query = [
  715. 'page' => '3000000000000000000000000',
  716. ];
  717. $table = TableRegistry::get('PaginatorPosts');
  718. $this->Paginator->paginate($table);
  719. }
  720. /**
  721. * test that fields not in whitelist won't be part of order conditions.
  722. *
  723. * @return void
  724. */
  725. public function testValidateSortWhitelistFailure()
  726. {
  727. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  728. $model->expects($this->any())
  729. ->method('alias')
  730. ->will($this->returnValue('model'));
  731. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  732. $options = [
  733. 'sort' => 'body',
  734. 'direction' => 'asc',
  735. 'sortWhitelist' => ['title', 'id']
  736. ];
  737. $result = $this->Paginator->validateSort($model, $options);
  738. $this->assertEquals([], $result['order']);
  739. }
  740. /**
  741. * test that fields in the whitelist are not validated
  742. *
  743. * @return void
  744. */
  745. public function testValidateSortWhitelistTrusted()
  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->once())
  752. ->method('hasField')
  753. ->will($this->returnValue(true));
  754. $options = [
  755. 'sort' => 'body',
  756. 'direction' => 'asc',
  757. 'sortWhitelist' => ['body']
  758. ];
  759. $result = $this->Paginator->validateSort($model, $options);
  760. $expected = ['model.body' => 'asc'];
  761. $this->assertEquals(
  762. $expected,
  763. $result['order'],
  764. 'Trusted fields in schema should be prefixed'
  765. );
  766. }
  767. /**
  768. * test that whitelist as empty array does not allow any sorting
  769. *
  770. * @return void
  771. */
  772. public function testValidateSortWhitelistEmpty()
  773. {
  774. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  775. $model->expects($this->any())
  776. ->method('alias')
  777. ->will($this->returnValue('model'));
  778. $model->expects($this->any())->method('hasField')
  779. ->will($this->returnValue(true));
  780. $options = [
  781. 'order' => [
  782. 'body' => 'asc',
  783. 'foo.bar' => 'asc'
  784. ],
  785. 'sort' => 'body',
  786. 'direction' => 'asc',
  787. 'sortWhitelist' => []
  788. ];
  789. $result = $this->Paginator->validateSort($model, $options);
  790. $this->assertSame([], $result['order'], 'No sort should be applied');
  791. }
  792. /**
  793. * test that fields in the whitelist are not validated
  794. *
  795. * @return void
  796. */
  797. public function testValidateSortWhitelistNotInSchema()
  798. {
  799. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  800. $model->expects($this->any())
  801. ->method('alias')
  802. ->will($this->returnValue('model'));
  803. $model->expects($this->once())->method('hasField')
  804. ->will($this->returnValue(false));
  805. $options = [
  806. 'sort' => 'score',
  807. 'direction' => 'asc',
  808. 'sortWhitelist' => ['score']
  809. ];
  810. $result = $this->Paginator->validateSort($model, $options);
  811. $expected = ['score' => 'asc'];
  812. $this->assertEquals(
  813. $expected,
  814. $result['order'],
  815. 'Trusted fields not in schema should not be altered'
  816. );
  817. }
  818. /**
  819. * test that multiple fields in the whitelist are not validated and properly aliased.
  820. *
  821. * @return void
  822. */
  823. public function testValidateSortWhitelistMultiple()
  824. {
  825. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  826. $model->expects($this->any())
  827. ->method('alias')
  828. ->will($this->returnValue('model'));
  829. $model->expects($this->once())
  830. ->method('hasField')
  831. ->will($this->returnValue(true));
  832. $options = [
  833. 'order' => [
  834. 'body' => 'asc',
  835. 'foo.bar' => 'asc'
  836. ],
  837. 'sortWhitelist' => ['body', 'foo.bar']
  838. ];
  839. $result = $this->Paginator->validateSort($model, $options);
  840. $expected = [
  841. 'model.body' => 'asc',
  842. 'foo.bar' => 'asc'
  843. ];
  844. $this->assertEquals($expected, $result['order']);
  845. }
  846. /**
  847. * test that multiple sort works.
  848. *
  849. * @return void
  850. */
  851. public function testValidateSortMultiple()
  852. {
  853. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  854. $model->expects($this->any())
  855. ->method('alias')
  856. ->will($this->returnValue('model'));
  857. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  858. $options = [
  859. 'order' => [
  860. 'author_id' => 'asc',
  861. 'title' => 'asc'
  862. ]
  863. ];
  864. $result = $this->Paginator->validateSort($model, $options);
  865. $expected = [
  866. 'model.author_id' => 'asc',
  867. 'model.title' => 'asc'
  868. ];
  869. $this->assertEquals($expected, $result['order']);
  870. }
  871. /**
  872. * Tests that order strings can used by Paginator
  873. *
  874. * @return void
  875. */
  876. public function testValidateSortWithString()
  877. {
  878. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  879. $model->expects($this->any())
  880. ->method('alias')
  881. ->will($this->returnValue('model'));
  882. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  883. $options = [
  884. 'order' => 'model.author_id DESC'
  885. ];
  886. $result = $this->Paginator->validateSort($model, $options);
  887. $expected = 'model.author_id DESC';
  888. $this->assertEquals($expected, $result['order']);
  889. }
  890. /**
  891. * Test that no sort doesn't trigger an error.
  892. *
  893. * @return void
  894. */
  895. public function testValidateSortNoSort()
  896. {
  897. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  898. $model->expects($this->any())
  899. ->method('alias')
  900. ->will($this->returnValue('model'));
  901. $model->expects($this->any())->method('hasField')
  902. ->will($this->returnValue(true));
  903. $options = [
  904. 'direction' => 'asc',
  905. 'sortWhitelist' => ['title', 'id'],
  906. ];
  907. $result = $this->Paginator->validateSort($model, $options);
  908. $this->assertEquals([], $result['order']);
  909. }
  910. /**
  911. * Test sorting with incorrect aliases on valid fields.
  912. *
  913. * @return void
  914. */
  915. public function testValidateSortInvalidAlias()
  916. {
  917. $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
  918. $model->expects($this->any())
  919. ->method('alias')
  920. ->will($this->returnValue('model'));
  921. $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
  922. $options = ['sort' => 'Derp.id'];
  923. $result = $this->Paginator->validateSort($model, $options);
  924. $this->assertEquals([], $result['order']);
  925. }
  926. /**
  927. * @return array
  928. */
  929. public function checkLimitProvider()
  930. {
  931. return [
  932. 'out of bounds' => [
  933. ['limit' => 1000000, 'maxLimit' => 100],
  934. 100,
  935. ],
  936. 'limit is nan' => [
  937. ['limit' => 'sheep!', 'maxLimit' => 100],
  938. 1,
  939. ],
  940. 'negative limit' => [
  941. ['limit' => '-1', 'maxLimit' => 100],
  942. 1,
  943. ],
  944. 'unset limit' => [
  945. ['limit' => null, 'maxLimit' => 100],
  946. 1,
  947. ],
  948. 'limit = 0' => [
  949. ['limit' => 0, 'maxLimit' => 100],
  950. 1,
  951. ],
  952. 'limit = 0 v2' => [
  953. ['limit' => 0, 'maxLimit' => 0],
  954. 1,
  955. ],
  956. 'limit = null' => [
  957. ['limit' => null, 'maxLimit' => 0],
  958. 1,
  959. ],
  960. 'bad input, results in 1' => [
  961. ['limit' => null, 'maxLimit' => null],
  962. 1,
  963. ],
  964. 'bad input, results in 1 v2' => [
  965. ['limit' => false, 'maxLimit' => false],
  966. 1,
  967. ],
  968. ];
  969. }
  970. /**
  971. * test that maxLimit is respected
  972. *
  973. * @dataProvider checkLimitProvider
  974. * @return void
  975. */
  976. public function testCheckLimit($input, $expected)
  977. {
  978. $result = $this->Paginator->checkLimit($input);
  979. $this->assertSame($expected, $result['limit']);
  980. }
  981. /**
  982. * Integration test for checkLimit() being applied inside paginate()
  983. *
  984. * @return void
  985. */
  986. public function testPaginateMaxLimit()
  987. {
  988. $this->loadFixtures('Posts');
  989. $table = TableRegistry::get('PaginatorPosts');
  990. $settings = [
  991. 'maxLimit' => 100,
  992. ];
  993. $this->request->query = [
  994. 'limit' => '1000'
  995. ];
  996. $this->Paginator->paginate($table, $settings);
  997. $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['limit']);
  998. $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['perPage']);
  999. $this->request->query = [
  1000. 'limit' => '10'
  1001. ];
  1002. $this->Paginator->paginate($table, $settings);
  1003. $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['limit']);
  1004. $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['perPage']);
  1005. }
  1006. /**
  1007. * test paginate() and custom find, to make sure the correct count is returned.
  1008. *
  1009. * @return void
  1010. */
  1011. public function testPaginateCustomFind()
  1012. {
  1013. $this->loadFixtures('Posts');
  1014. $titleExtractor = function ($result) {
  1015. $ids = [];
  1016. foreach ($result as $record) {
  1017. $ids[] = $record->title;
  1018. }
  1019. return $ids;
  1020. };
  1021. $table = TableRegistry::get('PaginatorPosts');
  1022. $data = ['author_id' => 3, 'title' => 'Fourth Post', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  1023. $result = $table->save(new Entity($data));
  1024. $this->assertNotEmpty($result);
  1025. $result = $this->Paginator->paginate($table);
  1026. $this->assertCount(4, $result, '4 rows should come back');
  1027. $this->assertEquals(['First Post', 'Second Post', 'Third Post', 'Fourth Post'], $titleExtractor($result));
  1028. $result = $this->request->params['paging']['PaginatorPosts'];
  1029. $this->assertEquals(4, $result['current']);
  1030. $this->assertEquals(4, $result['count']);
  1031. $settings = ['finder' => 'published'];
  1032. $result = $this->Paginator->paginate($table, $settings);
  1033. $this->assertCount(3, $result, '3 rows should come back');
  1034. $this->assertEquals(['First Post', 'Second Post', 'Third Post'], $titleExtractor($result));
  1035. $result = $this->request->params['paging']['PaginatorPosts'];
  1036. $this->assertEquals(3, $result['current']);
  1037. $this->assertEquals(3, $result['count']);
  1038. $settings = ['finder' => 'published', 'limit' => 2, 'page' => 2];
  1039. $result = $this->Paginator->paginate($table, $settings);
  1040. $this->assertCount(1, $result, '1 rows should come back');
  1041. $this->assertEquals(['Third Post'], $titleExtractor($result));
  1042. $result = $this->request->params['paging']['PaginatorPosts'];
  1043. $this->assertEquals(1, $result['current']);
  1044. $this->assertEquals(3, $result['count']);
  1045. $this->assertEquals(2, $result['pageCount']);
  1046. $settings = ['finder' => 'published', 'limit' => 2];
  1047. $result = $this->Paginator->paginate($table, $settings);
  1048. $this->assertCount(2, $result, '2 rows should come back');
  1049. $this->assertEquals(['First Post', 'Second Post'], $titleExtractor($result));
  1050. $result = $this->request->params['paging']['PaginatorPosts'];
  1051. $this->assertEquals(2, $result['current']);
  1052. $this->assertEquals(3, $result['count']);
  1053. $this->assertEquals(2, $result['pageCount']);
  1054. $this->assertTrue($result['nextPage']);
  1055. $this->assertFalse($result['prevPage']);
  1056. $this->assertEquals(2, $result['perPage']);
  1057. $this->assertNull($result['limit']);
  1058. }
  1059. /**
  1060. * test paginate() and custom find with fields array, to make sure the correct count is returned.
  1061. *
  1062. * @return void
  1063. */
  1064. public function testPaginateCustomFindFieldsArray()
  1065. {
  1066. $this->loadFixtures('Posts');
  1067. $table = TableRegistry::get('PaginatorPosts');
  1068. $data = ['author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'];
  1069. $table->save(new Entity($data));
  1070. $settings = [
  1071. 'finder' => 'list',
  1072. 'conditions' => ['PaginatorPosts.published' => 'Y'],
  1073. 'limit' => 2
  1074. ];
  1075. $results = $this->Paginator->paginate($table, $settings);
  1076. $result = $results->toArray();
  1077. $expected = [
  1078. 1 => 'First Post',
  1079. 2 => 'Second Post',
  1080. ];
  1081. $this->assertEquals($expected, $result);
  1082. $result = $this->request->params['paging']['PaginatorPosts'];
  1083. $this->assertEquals(2, $result['current']);
  1084. $this->assertEquals(3, $result['count']);
  1085. $this->assertEquals(2, $result['pageCount']);
  1086. $this->assertTrue($result['nextPage']);
  1087. $this->assertFalse($result['prevPage']);
  1088. }
  1089. /**
  1090. * test paginate() and custom finders to ensure the count + find
  1091. * use the custom type.
  1092. *
  1093. * @return void
  1094. */
  1095. public function testPaginateCustomFindCount()
  1096. {
  1097. $settings = [
  1098. 'finder' => 'published',
  1099. 'limit' => 2
  1100. ];
  1101. $table = $this->_getMockPosts(['query']);
  1102. $query = $this->_getMockFindQuery();
  1103. $table->expects($this->once())
  1104. ->method('query')
  1105. ->will($this->returnValue($query));
  1106. $query->expects($this->once())->method('applyOptions')
  1107. ->with([
  1108. 'limit' => 2,
  1109. 'page' => 1,
  1110. 'order' => [],
  1111. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1112. 'scope' => null,
  1113. ]);
  1114. $this->Paginator->paginate($table, $settings);
  1115. }
  1116. /**
  1117. * Tests that it is possible to pass an already made query object to
  1118. * paginate()
  1119. *
  1120. * @return void
  1121. */
  1122. public function testPaginateQuery()
  1123. {
  1124. $this->request->query = ['page' => '-1'];
  1125. $settings = [
  1126. 'PaginatorPosts' => [
  1127. 'contain' => ['PaginatorAuthor'],
  1128. 'maxLimit' => 10,
  1129. 'group' => 'PaginatorPosts.published',
  1130. 'order' => ['PaginatorPosts.id' => 'ASC']
  1131. ]
  1132. ];
  1133. $table = $this->_getMockPosts(['find']);
  1134. $query = $this->_getMockFindQuery($table);
  1135. $table->expects($this->never())->method('find');
  1136. $query->expects($this->once())
  1137. ->method('applyOptions')
  1138. ->with([
  1139. 'contain' => ['PaginatorAuthor'],
  1140. 'group' => 'PaginatorPosts.published',
  1141. 'limit' => 10,
  1142. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1143. 'page' => 1,
  1144. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1145. 'scope' => null,
  1146. ]);
  1147. $this->Paginator->paginate($query, $settings);
  1148. }
  1149. /**
  1150. * test paginate() with bind()
  1151. *
  1152. * @return void
  1153. */
  1154. public function testPaginateQueryWithBindValue()
  1155. {
  1156. $config = ConnectionManager::config('test');
  1157. $this->skipIf(strpos($config['driver'], 'Sqlserver') !== false, 'Test temporarily broken in SQLServer');
  1158. $this->loadFixtures('Posts');
  1159. $table = TableRegistry::get('PaginatorPosts');
  1160. $query = $table->find()
  1161. ->where(['PaginatorPosts.author_id BETWEEN :start AND :end'])
  1162. ->bind(':start', 1)
  1163. ->bind(':end', 2);
  1164. $results = $this->Paginator->paginate($query, []);
  1165. $result = $results->toArray();
  1166. $this->assertCount(2, $result);
  1167. $this->assertEquals('First Post', $result[0]->title);
  1168. $this->assertEquals('Third Post', $result[1]->title);
  1169. }
  1170. /**
  1171. * Tests that passing a query object with a limit clause set will
  1172. * overwrite it with the passed defaults.
  1173. *
  1174. * @return void
  1175. */
  1176. public function testPaginateQueryWithLimit()
  1177. {
  1178. $this->request->query = ['page' => '-1'];
  1179. $settings = [
  1180. 'PaginatorPosts' => [
  1181. 'contain' => ['PaginatorAuthor'],
  1182. 'maxLimit' => 10,
  1183. 'limit' => 5,
  1184. 'group' => 'PaginatorPosts.published',
  1185. 'order' => ['PaginatorPosts.id' => 'ASC']
  1186. ]
  1187. ];
  1188. $table = $this->_getMockPosts(['find']);
  1189. $query = $this->_getMockFindQuery($table);
  1190. $query->limit(2);
  1191. $table->expects($this->never())->method('find');
  1192. $query->expects($this->once())
  1193. ->method('applyOptions')
  1194. ->with([
  1195. 'contain' => ['PaginatorAuthor'],
  1196. 'group' => 'PaginatorPosts.published',
  1197. 'limit' => 5,
  1198. 'order' => ['PaginatorPosts.id' => 'ASC'],
  1199. 'page' => 1,
  1200. 'whitelist' => ['limit', 'sort', 'page', 'direction'],
  1201. 'scope' => null,
  1202. ]);
  1203. $this->Paginator->paginate($query, $settings);
  1204. }
  1205. /**
  1206. * Helper method for making mocks.
  1207. *
  1208. * @param array $methods
  1209. * @return \Cake\ORM\Table|\PHPUnit_Framework_MockObject_MockObject
  1210. */
  1211. protected function _getMockPosts($methods = [])
  1212. {
  1213. return $this->getMockBuilder('TestApp\Model\Table\PaginatorPostsTable')
  1214. ->setMethods($methods)
  1215. ->setConstructorArgs([[
  1216. 'connection' => ConnectionManager::get('test'),
  1217. 'alias' => 'PaginatorPosts',
  1218. 'schema' => [
  1219. 'id' => ['type' => 'integer'],
  1220. 'author_id' => ['type' => 'integer', 'null' => false],
  1221. 'title' => ['type' => 'string', 'null' => false],
  1222. 'body' => 'text',
  1223. 'published' => ['type' => 'string', 'length' => 1, 'default' => 'N'],
  1224. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  1225. ]
  1226. ]])
  1227. ->getMock();
  1228. }
  1229. /**
  1230. * Helper method for mocking queries.
  1231. *
  1232. * @param string|null $table
  1233. *
  1234. * @return \Cake\ORM\Query|\PHPUnit_Framework_MockObject_MockObject
  1235. */
  1236. protected function _getMockFindQuery($table = null)
  1237. {
  1238. $query = $this->getMockBuilder('Cake\ORM\Query')
  1239. ->setMethods(['total', 'all', 'count', 'applyOptions'])
  1240. ->disableOriginalConstructor()
  1241. ->getMock();
  1242. $results = $this->getMockBuilder('Cake\ORM\ResultSet')
  1243. ->disableOriginalConstructor()
  1244. ->getMock();
  1245. $query->expects($this->any())
  1246. ->method('count')
  1247. ->will($this->returnValue(2));
  1248. $query->expects($this->any())
  1249. ->method('all')
  1250. ->will($this->returnValue($results));
  1251. $query->expects($this->any())
  1252. ->method('count')
  1253. ->will($this->returnValue(2));
  1254. $query->repository($table);
  1255. return $query;
  1256. }
  1257. }