Skip to content

Commit 249163f

Browse files
committed
feat: prevent state leakage in nested transformers with transformRelated()
1 parent a622750 commit 249163f

1 file changed

Lines changed: 30 additions & 1 deletion

File tree

‎system/API/BaseTransformer.php‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@
4848
* protected function includePosts(): array
4949
* {
5050
* $posts = model('PostModel')->where('user_id', $this->resource['id'])->findAll();
51-
* return (new PostTransformer())->transformMany($posts);
51+
*
52+
* // Use transformRelated() to safely transform nested resources
53+
* // without leaking the parent's request state (fields/includes).
54+
* return $this->transformRelated(PostTransformer::class, $posts);
5255
* }
5356
* }
5457
*/
@@ -124,6 +127,32 @@ public function transformMany(array $resources): array
124127
return array_map($this->transform(...), $resources);
125128
}
126129

130+
/**
131+
* Transforms related resources using a fresh, isolated transformer.
132+
* Automatically determines whether to use transform() or transformMany().
133+
*
134+
* @param class-string<TransformerInterface>|TransformerInterface $transformer
135+
* @param array<int|string, mixed>|object|null $resources
136+
*
137+
* @return array<int, array<string, mixed>>|array<string, mixed>
138+
*/
139+
protected function transformRelated(string|TransformerInterface $transformer, mixed $resources): array
140+
{
141+
$instance = is_string($transformer) ? new $transformer() : $transformer;
142+
143+
if ($instance instanceof self) {
144+
// Prevent Global State Leakage silently.
145+
$instance->fields = null;
146+
$instance->includes = null;
147+
}
148+
149+
if (is_array($resources) && array_is_list($resources)) {
150+
return $instance->transformMany($resources);
151+
}
152+
153+
return $instance->transform($resources);
154+
}
155+
127156
/**
128157
* Define which fields can be requested via the 'fields' query parameter.
129158
* Override in child classes to restrict available fields.

0 commit comments

Comments
 (0)