Skip to content

A free open source IT asset/license management system

Small follow-up to #19236

snipe1149c96b2af2
diff --git a/app/Http/Controllers/Api/UploadedFilesController.php b/app/Http/Controllers/Api/UploadedFilesController.php
index 5fb1956df9..9de28b595a 100644
--- a/app/Http/Controllers/Api/UploadedFilesController.php
+++ b/app/Http/Controllers/Api/UploadedFilesController.php
@@ -52,7 +52,6 @@ class UploadedFilesController extends Controller
$uploads = self::$map_object_type[$object_type]::withTrashed()->find($id)->uploads()
->with('adminuser');
- $offset = ($request->input('offset') > $uploads->count()) ? $uploads->count() : app('api_offset_value');
$limit = app('api_limit_value');
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array($request->input('sort'), $allowed_columns) ? $request->input('sort') : 'created_at';
@@ -70,7 +69,12 @@ class UploadedFilesController extends Controller
);
}
+ // $total must be computed after the search where() block so both
+ // the offset clamp and the response total reflect the filtered
+ // set. Previously the offset ran on the unfiltered count, which
+ // could over-clamp when a search narrowed results.
$total = $uploads->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
$uploads = $uploads->skip($offset)->take($limit)->orderBy($sort, $order)->get();
return (new UploadedFilesTransformer)->transformFiles($uploads, $total);
diff --git a/tests/Feature/Assets/Api/UploadedFilesPaginationTest.php b/tests/Feature/Assets/Api/UploadedFilesPaginationTest.php
index d21f1dfcae..8b843b874d 100644
--- a/tests/Feature/Assets/Api/UploadedFilesPaginationTest.php
+++ b/tests/Feature/Assets/Api/UploadedFilesPaginationTest.php
@@ -121,6 +121,34 @@ class UploadedFilesPaginationTest extends TestCase
$this->assertCount(4, $response->json('rows'));
}
+ public function test_search_filter_reflects_filtered_total_not_unfiltered_count()
+ {
+ // Regression: total (and the offset clamp that depends on it)
+ // used to be computed from the unfiltered query, so a search
+ // that narrowed 10 rows down to 2 still reported total=10.
+ foreach (range(1, 10) as $i) {
+ $this->createUploadLog(sprintf('PAG-TEST-%03d.jpg', $i));
+ }
+ $this->createUploadLog('needle-one.jpg');
+ $this->createUploadLog('needle-two.jpg');
+
+ $response = $this->actingAsForApi($this->user)
+ ->getJson(route('api.files.index', [
+ 'object_type' => 'assets',
+ 'id' => $this->asset->id,
+ 'search' => 'needle',
+ 'sort' => 'filename',
+ 'order' => 'asc',
+ ]))
+ ->assertOk();
+
+ $this->assertEquals(2, $response->json('total'));
+ $this->assertEquals(
+ ['needle-one.jpg', 'needle-two.jpg'],
+ $response->json('rows.*.filename'),
+ );
+ }
+
public function test_page_beyond_results_returns_empty_rows()
{
foreach (range(1, 5) as $i) {