PaginatorComponentTest.php 39 KB

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