|
48 | 48 | * protected function includePosts(): array |
49 | 49 | * { |
50 | 50 | * $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); |
52 | 55 | * } |
53 | 56 | * } |
54 | 57 | */ |
@@ -124,6 +127,32 @@ public function transformMany(array $resources): array |
124 | 127 | return array_map($this->transform(...), $resources); |
125 | 128 | } |
126 | 129 |
|
| 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 | + |
127 | 156 | /** |
128 | 157 | * Define which fields can be requested via the 'fields' query parameter. |
129 | 158 | * Override in child classes to restrict available fields. |
|
0 commit comments