Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelogs/v4.7.7.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 13 additions & 4 deletions system/API/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
}

Expand Down
192 changes: 192 additions & 0 deletions tests/system/API/ResponseTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
Loading