PaginatorComponentTest.php 42 KB

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