PaginatorComponentTest.php 42 KB

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