PaginatorComponentTest.php 42 KB

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