PaginatedCollectionTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace Test\Unit;
  3. require_once dirname(__DIR__) . '/Setup.php';
  4. use Test\Setup;
  5. use Braintree;
  6. class Pager {
  7. private $_pagingFunc;
  8. public function __construct($pagingFunc) {
  9. $this->_pagingFunc = $pagingFunc;
  10. }
  11. public function page ($page) {
  12. return call_user_func($this->_pagingFunc, $page);
  13. }
  14. }
  15. class PaginatedCollectionTest extends Setup
  16. {
  17. public function testFetchesOnePageWhenPageAndTotalSizesMatch()
  18. {
  19. $pager = [
  20. 'object' => new Pager(function ($page) {
  21. if ($page > 1)
  22. {
  23. throw new \Exception('too many pages fetched');
  24. }
  25. else
  26. {
  27. return new Braintree\PaginatedResult(1, 1, [1]);
  28. }
  29. }),
  30. 'method' => 'page',
  31. ];
  32. $collection = new Braintree\PaginatedCollection($pager);
  33. $items = [];
  34. foreach($collection as $item)
  35. {
  36. array_push($items, $item);
  37. }
  38. $this->assertEquals(1, $items[0]);
  39. $this->assertEquals(1, count($items));
  40. }
  41. public function testFetchCollectionOfLessThanOnePage()
  42. {
  43. $pager = [
  44. 'object' => new Pager(function ($page) {
  45. if ($page > 1)
  46. {
  47. throw new \Exception('too many pages fetched');
  48. }
  49. else
  50. {
  51. return new Braintree\PaginatedResult(2, 5, [1, 2]);
  52. }
  53. }),
  54. 'method' => 'page',
  55. ];
  56. $collection = new Braintree\PaginatedCollection($pager);
  57. $items = [];
  58. foreach($collection as $item)
  59. {
  60. array_push($items, $item);
  61. }
  62. $this->assertEquals(1, $items[0]);
  63. $this->assertEquals(2, $items[1]);
  64. $this->assertEquals(2, count($items));
  65. }
  66. public function testFetchesMultiplePages()
  67. {
  68. $pager = [
  69. 'object' => new Pager(function ($page) {
  70. if ($page > 2)
  71. {
  72. throw new \Exception('too many pages fetched');
  73. }
  74. else
  75. {
  76. return new Braintree\PaginatedResult(2, 1, [$page]);
  77. }
  78. }),
  79. 'method' => 'page',
  80. ];
  81. $collection = new Braintree\PaginatedCollection($pager);
  82. $items = [];
  83. foreach($collection as $item)
  84. {
  85. array_push($items, $item);
  86. }
  87. $this->assertEquals(1, $items[0]);
  88. $this->assertEquals(2, $items[1]);
  89. $this->assertEquals(2, count($items));
  90. }
  91. }