diff --git a/src/Paginators/EmptyPaginator.php b/src/Paginators/EmptyPaginator.php new file mode 100644 index 0000000..5ff2d59 --- /dev/null +++ b/src/Paginators/EmptyPaginator.php @@ -0,0 +1,33 @@ +items = $items instanceof Collection ? $items : Collection::make($items); + $this->total = 0; + } + + public function toArray() + { + return [ + 'data' => $this->items->toArray(), + 'from' => $this->firstItem(), + 'path' => $this->path, + 'to' => $this->lastItem(), + 'total' => $this->total(), + ]; + } + + public function total() + { + return $this->total; + } +} diff --git a/src/Repositories/BaseApiRepository.php b/src/Repositories/BaseApiRepository.php index 3f8e4da..f232de5 100644 --- a/src/Repositories/BaseApiRepository.php +++ b/src/Repositories/BaseApiRepository.php @@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Pagination\LengthAwarePaginator; use Swis\JsonApi\Server\Exceptions\NotFoundException; +use Swis\JsonApi\Server\Paginators\EmptyPaginator; use Swis\JsonApi\Server\Traits\HandlesRelationships; abstract class BaseApiRepository implements RepositoryInterface @@ -47,6 +48,9 @@ public function paginate($parameters = []) if (array_key_exists('all', $this->parameters)) { $collection = $this->query->get(); $total = count($collection); + if (0 == $total) { + return new EmptyPaginator(); + } return new LengthAwarePaginator($collection, $total, $total); } diff --git a/tests/Unit/EmptyPaginatorTest.php b/tests/Unit/EmptyPaginatorTest.php new file mode 100644 index 0000000..f361a25 --- /dev/null +++ b/tests/Unit/EmptyPaginatorTest.php @@ -0,0 +1,29 @@ +emptyPaginator = new EmptyPaginator(); + } + + /** @test */ + public function test_total() + { + $this->assertEquals(0, $this->emptyPaginator->total()); + } + + /** @test */ + public function test_to_array() + { + $this->assertEquals([], $this->emptyPaginator->toArray()['data']); + $this->assertEquals(0, $this->emptyPaginator->toArray()['total']); + } +} diff --git a/tests/Unit/RepositoryTest.php b/tests/Unit/RepositoryTest.php index 9b84bf0..8bd57f4 100644 --- a/tests/Unit/RepositoryTest.php +++ b/tests/Unit/RepositoryTest.php @@ -4,6 +4,7 @@ use Illuminate\Database\Eloquent\ModelNotFoundException; use Swis\JsonApi\Server\Exceptions\NotFoundException; +use Swis\JsonApi\Server\Paginators\EmptyPaginator; use Tests\TestCase; use Tests\TestClasses\TestModel; use Tests\TestClasses\TestRepository; @@ -118,6 +119,13 @@ public function paginate_with_all_attribute() $this->assertEquals(1, $this->testRepository->paginate($parameters = ['all' => true])->total()); } + /** @test */ + public function paginate_with_all_attribute_empty_collection() + { + $result = $this->testRepositoryWithRelationships->paginate(['all' => true]); + $this->assertInstanceOf(EmptyPaginator::class, $result); + } + /** @test */ public function set_columns() {