Skip to content

Commit 0c5c3ad

Browse files
authored
feat: add per-type API transformer sparse fieldsets (#10285)
1 parent f889329 commit 0c5c3ad

7 files changed

Lines changed: 281 additions & 11 deletions

File tree

‎system/API/BaseTransformer.php‎

Lines changed: 68 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
* - fields: Comma-separated list of fields to include in the response
2626
* (e.g., ?fields=id,name,email)
2727
* If not provided, all fields from toArray() are included.
28+
* Since v4.8.0, per-type sparse fieldsets are also supported via the
29+
* bracketed form (e.g., ?fields[posts]=id,slug). A transformer reads the
30+
* fieldset that matches its declared $resourceType, so a nested
31+
* PostTransformer with $resourceType = 'posts' applies ?fields[posts]=...
32+
* while the root resource is unaffected.
2833
* - include: Comma-separated list of related resources to include
2934
* (e.g., ?include=posts,comments)
3035
* This looks for methods named `include{Resource}()` on the transformer,
@@ -69,6 +74,11 @@ abstract class BaseTransformer implements TransformerInterface
6974
*/
7075
private ?array $includes = null;
7176

77+
/**
78+
* Resource type used to resolve per-type sparse fieldsets.
79+
*/
80+
protected ?string $resourceType = null;
81+
7282
protected mixed $resource = null;
7383

7484
public function __construct(
@@ -82,16 +92,65 @@ public function __construct(
8292
$this->request = $request ?? request();
8393

8494
if ($explicitRequest || self::$depth === 0) {
85-
$fields = $this->request->getGet('fields');
86-
$this->fields = is_string($fields)
87-
? array_map(trim(...), explode(',', $fields))
88-
: $fields;
89-
90-
$includes = $this->request->getGet('include');
91-
$this->includes = is_string($includes)
92-
? array_map(trim(...), explode(',', $includes))
93-
: $includes;
95+
$this->fields = $this->resolveFields(true);
96+
$this->includes = $this->resolveIncludes();
97+
} elseif ($this->resourceType !== null) {
98+
$this->fields = $this->resolveFields(false);
99+
}
100+
}
101+
102+
/**
103+
* Resolves the requested field list for this transformer from the request.
104+
*
105+
* Supports both the flat `?fields=a,b` form and the per-type sparse
106+
* fieldset form `?fields[<type>]=a,b`. The flat form is only honored when
107+
* $allowFlat is true (i.e. for the root transformer); a type-specific
108+
* fieldset is matched against this transformer's $resourceType at any
109+
* nesting level.
110+
*
111+
* @return list<string>|null
112+
*/
113+
private function resolveFields(bool $allowFlat): ?array
114+
{
115+
$fields = $this->request->getGet('fields');
116+
117+
// Sparse fieldsets: ?fields[posts]=id,slug -> ['posts' => 'id,slug']
118+
if (is_array($fields)) {
119+
$scoped = ($this->resourceType !== null && is_string($fields[$this->resourceType] ?? null))
120+
? $fields[$this->resourceType]
121+
: null;
122+
123+
return $scoped !== null ? $this->splitList($scoped) : null;
124+
}
125+
126+
// Flat fieldset: ?fields=id,slug (applies to the root only)
127+
if ($allowFlat && is_string($fields)) {
128+
return $this->splitList($fields);
94129
}
130+
131+
return null;
132+
}
133+
134+
/**
135+
* Resolves the requested include list from the request's `include` param.
136+
*
137+
* @return list<string>|null
138+
*/
139+
private function resolveIncludes(): ?array
140+
{
141+
$includes = $this->request->getGet('include');
142+
143+
return is_string($includes) ? $this->splitList($includes) : $includes;
144+
}
145+
146+
/**
147+
* Splits a comma-separated query value into a list of trimmed strings.
148+
*
149+
* @return list<string>
150+
*/
151+
private function splitList(string $value): array
152+
{
153+
return array_map(trim(...), explode(',', $value));
95154
}
96155

97156
/**

‎tests/_support/API/ChildTransformer.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
*/
2222
class ChildTransformer extends BaseTransformer
2323
{
24+
protected ?string $resourceType = 'child';
25+
2426
public function toArray(mixed $resource): array
2527
{
2628
return [

‎tests/_support/API/ParentTransformer.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
*/
2222
class ParentTransformer extends BaseTransformer
2323
{
24+
protected ?string $resourceType = 'parent';
25+
2426
public function toArray(mixed $resource): array
2527
{
2628
return [

‎tests/system/API/TransformerTest.php‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -801,4 +801,125 @@ public function testBareNestedTransformerStillUsedByChildTransformerDirectly():
801801

802802
$this->assertSame(['child_id' => 42], $result);
803803
}
804+
805+
public function testSparseFieldsetScopesNestedChildByType(): void
806+
{
807+
// ?fields[child]=child_id must scope the nested ChildTransformer
808+
// ($resourceType = 'child') automatically, without any explicit request.
809+
$request = $this->createMockRequest('include=children&fields[child]=child_id');
810+
Services::injectMock('request', $request);
811+
812+
$transformer = new ParentTransformer($request);
813+
814+
$result = $transformer->transform(['id' => 1]);
815+
816+
$this->assertSame([
817+
'parent_id' => 1,
818+
'children' => ['child_id' => 99], // 'status' dropped by fields[child]
819+
], $result);
820+
}
821+
822+
public function testSparseFieldsetForOneTypeLeavesOthersUntouched(): void
823+
{
824+
// ?fields[parent]=parent_id scopes only the root; the child is full.
825+
$request = $this->createMockRequest('include=children&fields[parent]=parent_id');
826+
Services::injectMock('request', $request);
827+
828+
$transformer = new ParentTransformer($request);
829+
830+
$result = $transformer->transform(['id' => 1]);
831+
832+
$this->assertSame([
833+
'parent_id' => 1,
834+
'children' => ['child_id' => 99, 'status' => 'transformed'],
835+
], $result);
836+
}
837+
838+
public function testSparseFieldsetsScopeRootAndChildIndependently(): void
839+
{
840+
// The headline case: each type gets its own fieldset in one request.
841+
$request = $this->createMockRequest('include=children&fields[parent]=parent_id&fields[child]=child_id');
842+
Services::injectMock('request', $request);
843+
844+
$transformer = new ParentTransformer($request);
845+
846+
$result = $transformer->transform(['id' => 1]);
847+
848+
$this->assertSame([
849+
'parent_id' => 1,
850+
'children' => ['child_id' => 99],
851+
], $result);
852+
}
853+
854+
public function testFlatFieldsDoesNotScopeTypedNestedChild(): void
855+
{
856+
// A flat ?fields= belongs to the root only and must not leak into a
857+
// typed nested child.
858+
$request = $this->createMockRequest('include=children&fields=parent_id');
859+
Services::injectMock('request', $request);
860+
861+
$transformer = new ParentTransformer($request);
862+
863+
$result = $transformer->transform(['id' => 1]);
864+
865+
$this->assertSame([
866+
'parent_id' => 1,
867+
'children' => ['child_id' => 99, 'status' => 'transformed'],
868+
], $result);
869+
}
870+
871+
public function testUnknownSparseFieldsetIsIgnored(): void
872+
{
873+
// A fieldset for a type not present in the response is simply ignored;
874+
// every transformer returns all of its fields.
875+
$request = $this->createMockRequest('include=children&fields[unknown]=id');
876+
Services::injectMock('request', $request);
877+
878+
$transformer = new ParentTransformer($request);
879+
880+
$result = $transformer->transform(['id' => 1]);
881+
882+
$this->assertSame([
883+
'parent_id' => 1,
884+
'children' => ['child_id' => 99, 'status' => 'transformed'],
885+
], $result);
886+
}
887+
888+
public function testSparseFieldsetAppliesToRootWhenTypeMatches(): void
889+
{
890+
// ?fields[child]=child_id on a root ChildTransformer ($resourceType = 'child').
891+
$request = $this->createMockRequest('fields[child]=child_id');
892+
Services::injectMock('request', $request);
893+
894+
$transformer = new ChildTransformer($request);
895+
896+
$result = $transformer->transform(['id' => 42]);
897+
898+
$this->assertSame(['child_id' => 42], $result);
899+
}
900+
901+
public function testSparseFieldsetRespectsAllowedFieldsWhitelist(): void
902+
{
903+
$this->expectException(ApiException::class);
904+
$this->expectExceptionMessage(lang('Api.invalidFields', ['secret']));
905+
906+
$request = $this->createMockRequest('fields[widget]=id,secret');
907+
Services::injectMock('request', $request);
908+
909+
$transformer = new class ($request) extends BaseTransformer {
910+
protected ?string $resourceType = 'widget';
911+
912+
public function toArray(mixed $resource): array
913+
{
914+
return $resource;
915+
}
916+
917+
protected function getAllowedFields(): array
918+
{
919+
return ['id', 'name'];
920+
}
921+
};
922+
923+
$transformer->transform(['id' => 1, 'name' => 'Test', 'secret' => 'x']);
924+
}
804925
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,14 @@ Removed Deprecated Items
182182
Enhancements
183183
************
184184

185+
API
186+
===
187+
188+
- Added per-type sparse fieldsets to API transformers. A transformer may declare a ``$type`` so clients
189+
can request ``?fields[<type>]=...`` to filter the fields of that resource type independently, including
190+
for nested/related resources, while the flat ``?fields=...`` continues to apply to the root resource only.
191+
See :ref:`api_transformers`.
192+
185193
Commands
186194
========
187195

‎user_guide_src/source/outgoing/api_transformers.rst‎

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,50 @@ fields are allowed by overriding the ``getAllowedFields()`` method:
129129
Now, even if a client requests ``/users/1?fields=email``, an ``ApiException`` will be thrown because
130130
``email`` is not in the allowed fields list.
131131

132+
Sparse Fieldsets (Per-Type Filtering)
133+
=====================================
134+
135+
.. versionadded:: 4.8.0
136+
137+
The flat ``fields`` parameter filters the root resource. When a response also embeds
138+
:ref:`related resources <api_transformers_includes>`, you can filter each related type
139+
independently using the bracketed *sparse fieldset* form ``fields[<type>]=...``.
140+
141+
To opt a transformer into this, declare its resource type via the ``$resourceType`` property:
142+
143+
.. literalinclude:: api_transformers/024.php
144+
145+
A matching ``fields[<type>]`` fieldset applies whether the transformer is used as the root resource or
146+
as an included resource. The flat ``fields=...`` form still applies to the root transformer only.
147+
148+
Each transformer reads the fieldset that matches its own ``$resourceType``. Given the ``UserTransformer``
149+
from :ref:`Including Related Resources <api_transformers_includes>` (which includes posts), a request:
150+
151+
.. code-block:: text
152+
153+
/users/1?include=posts&fields[posts]=id,slug
154+
155+
scopes the fields **only** for the embedded posts, leaving the user fields untouched:
156+
157+
.. code-block:: json
158+
159+
{
160+
"id": 1,
161+
"name": "John Doe",
162+
"email": "john@example.com",
163+
"posts": [
164+
{
165+
"id": 1,
166+
"slug": "first-post"
167+
}
168+
]
169+
}
170+
171+
When filtering multiple resource types in one request, use the bracketed form for each type, such as
172+
``fields[users]=id,name&fields[posts]=id,slug``.
173+
174+
.. _api_transformers_includes:
175+
132176
***************************
133177
Including Related Resources
134178
***************************
@@ -174,10 +218,11 @@ The response would include:
174218
]
175219
}
176220
177-
.. note:: The ``fields`` and ``include`` query parameters describe the **root** resource only.
221+
.. note:: The flat ``fields=...`` and ``include`` query parameters describe the **root** resource only.
178222
Transformers instantiated inside an ``include*()`` method (such as ``PostTransformer`` above)
179223
are treated as nested resources: when created **without an explicit request** they do **not**
180-
inherit the root request's ``fields``/``include`` state. This prevents the parent's query
224+
inherit the root request's flat ``fields``/``include`` state. Use ``fields[<type>]=...`` with
225+
a matching ``$resourceType`` to filter a nested resource. This prevents the parent's query
181226
parameters from leaking into related resources, which could otherwise cause incorrect field
182227
filtering or unexpected/recursive includes. If you deliberately pass a request to a nested
183228
transformer, that request's scope is honored.
@@ -264,6 +309,17 @@ Class Reference
264309
265310
.. php:class:: BaseTransformer
266311
312+
.. php:attr:: $resourceType
313+
314+
:type: string|null
315+
316+
.. versionadded:: 4.8.0
317+
318+
The resource type this transformer represents. Used to resolve per-type sparse fieldsets from
319+
the request (e.g. a type of ``'posts'`` reads ``?fields[posts]=...``). Defaults to ``null``,
320+
in which case only the flat ``?fields=...`` parameter applies, and only to the root transformer.
321+
See `Sparse Fieldsets (Per-Type Filtering)`_.
322+
267323
.. php:method:: __construct(?IncomingRequest $request = null)
268324
269325
:param IncomingRequest|null $request: Optional request instance. If not provided, the global request will be used.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace App\Transformers;
4+
5+
use CodeIgniter\API\BaseTransformer;
6+
7+
class PostTransformer extends BaseTransformer
8+
{
9+
// Enables ?fields[posts]=... for this resource type.
10+
protected ?string $resourceType = 'posts';
11+
12+
public function toArray(mixed $resource): array
13+
{
14+
return [
15+
'id' => $resource['id'],
16+
'title' => $resource['title'],
17+
'slug' => $resource['slug'],
18+
'body' => $resource['body'],
19+
'user_id' => $resource['user_id'],
20+
];
21+
}
22+
}

0 commit comments

Comments
 (0)