diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index d817d9932f94..3f440e313493 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -18,6 +18,7 @@ Release Date: Unreleased ## Bugs Fixed +- **API:** Fixed HTTP 500 errors in `ResponseTrait::paginate()` when using a Query Builder with a very large page number or `$perPage = 0`. - **Cache:** Fixed a bug where `PredisHandler::increment()` and `PredisHandler::decrement()` updated the unused `'data'` hash field instead of `'__ci_value'`, causing `get()` to return stale values for existing counters. - **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers. - **Database:** Fixed a bug where `Postgre`, `OCI8`, and `SQLSRV` `Forge::_dropKeyAsConstraint()` interpolated table, constraint, and schema names without escaping. diff --git a/system/API/ResponseTrait.php b/system/API/ResponseTrait.php index 0449e91bf07c..4cc5905934ce 100644 --- a/system/API/ResponseTrait.php +++ b/system/API/ResponseTrait.php @@ -416,15 +416,24 @@ protected function paginate(BaseBuilder|Model $resource, int $perPage = 20, ?str ]; } else { // Query Builder, we need to handle pagination manually - $offset = ($page - 1) * $perPage; - $total = (clone $resource)->countAllResults(); - $data = $resource->limit($perPage, $offset)->get()->getResultArray(); + $total = (int) (clone $resource)->countAllResults(); + + if ($perPage > 0) { + $totalPages = (int) ceil($total / $perPage); + + $offset = $page > $totalPages ? $total : ($page - 1) * $perPage; + } else { + $totalPages = 0; + $offset = 0; + } + + $data = $resource->limit($perPage, $offset)->get()->getResultArray(); $meta = [ 'page' => $page, 'perPage' => $perPage, 'total' => $total, - 'totalPages' => (int) ceil($total / $perPage), + 'totalPages' => $totalPages, ]; } diff --git a/tests/system/API/ResponseTraitTest.php b/tests/system/API/ResponseTraitTest.php index f5d33491a655..93ded944c350 100644 --- a/tests/system/API/ResponseTraitTest.php +++ b/tests/system/API/ResponseTraitTest.php @@ -799,6 +799,198 @@ public function testPaginateWithQueryBuilder(): void $this->assertSame(3, $responseBody['meta']['totalPages']); } + public function testPaginateWithQueryBuilderOutOfRangePage(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(50); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 50) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); + + $controller = $this->makeController('/api/items?page=4'); + $this->request->setGlobal('get', ['page' => '4']); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame([], $responseBody['data']); + $this->assertSame(4, $responseBody['meta']['page']); + $this->assertSame(20, $responseBody['meta']['perPage']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(3, $responseBody['meta']['totalPages']); + $this->assertStringContainsString('page=4', (string) $responseBody['links']['self']); + $this->assertNull($responseBody['links']['next']); + $this->assertStringContainsString('page=3', (string) $responseBody['links']['prev']); + } + + public function testPaginateWithQueryBuilderPageOverflow(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(50); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 50) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); + + $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); + $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(PHP_INT_MAX, $responseBody['meta']['page']); + $this->assertSame(20, $responseBody['meta']['perPage']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(3, $responseBody['meta']['totalPages']); + $this->assertSame([], $responseBody['data']); + $this->assertNull($responseBody['links']['next']); + } + + public function testPaginateWithQueryBuilderZeroResultsPageOverflow(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(0); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 0) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); + + $controller = $this->makeController('/api/items?page=' . PHP_INT_MAX); + $this->request->setGlobal('get', ['page' => (string) PHP_INT_MAX]); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(PHP_INT_MAX, $responseBody['meta']['page']); + $this->assertSame(0, $responseBody['meta']['total']); + $this->assertSame(0, $responseBody['meta']['totalPages']); + $this->assertSame([], $responseBody['data']); + } + + public function testPaginateWithQueryBuilderZeroPerPage(): void + { + // Mock the database and builder + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + $data = [ + ['id' => 1], + ['id' => 2], + ]; + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn(50); + $builder->expects($this->once()) + ->method('limit') + ->with(0, 0) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn($data); + + $controller = $this->makeController('/api/items'); + + $this->invoke($controller, 'paginate', [$builder, 0]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(200, $this->response->getStatusCode()); + $this->assertSame(1, $responseBody['meta']['page']); + $this->assertSame(0, $responseBody['meta']['perPage']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(0, $responseBody['meta']['totalPages']); + $this->assertSame($data, $responseBody['data']); + } + + public function testPaginateWithQueryBuilderStringTotalFromCountAllResults(): void + { + $db = $this->createStub(BaseConnection::class); + + $builder = $this->getMockBuilder(BaseBuilder::class) + ->setConstructorArgs(['test_table', $db]) + ->onlyMethods(['countAllResults', 'limit', 'get']) + ->getMock(); + + $result = $this->createMock(BaseResult::class); + + // Mock the query builder chain + $builder->method('countAllResults')->willReturn('50'); + $builder->expects($this->once()) + ->method('limit') + ->with(20, 50) + ->willReturnSelf(); + $builder->expects($this->once()) + ->method('get') + ->willReturn($result); + $result->method('getResultArray')->willReturn([]); + + $controller = $this->makeController('/api/items?page=4'); + $this->request->setGlobal('get', ['page' => '4']); + + $this->invoke($controller, 'paginate', [$builder, 20]); + + $responseBody = json_decode($this->response->getBody(), true); + + $this->assertSame(200, $this->response->getStatusCode()); + $this->assertSame([], $responseBody['data']); + $this->assertSame(4, $responseBody['meta']['page']); + $this->assertSame(50, $responseBody['meta']['total']); + $this->assertSame(3, $responseBody['meta']['totalPages']); + } + public function testPaginateWithCustomPerPage(): void { $data = [