@@ -139,4 +139,102 @@ public function find(int $id): array
139139 ;
140140 });
141141 });
142+
143+ describe ('Anonymous Class Variable Scope Isolation ' , function () {
144+ test ('does not leak outer variable type contracts into anonymous class method local variables ' , function () {
145+ /** @var positive-int $leaked */
146+ $ leaked = 100 ;
147+
148+ $ anon = new class () {
149+ public function process (): string
150+ {
151+ $ leaked = 'string_inside_anonymous_class_method ' ;
152+
153+ return $ leaked ;
154+ }
155+ };
156+
157+ expect ($ anon ->process ())->toBe ('string_inside_anonymous_class_method ' )
158+ ->and ($ leaked )->toBe (100 )
159+ ;
160+ });
161+
162+ test ('does not leak outer variable type contracts into anonymous class method parameter reassignment ' , function () {
163+ /** @var positive-int $label */
164+ $ label = 42 ;
165+
166+ $ anon = new class () {
167+ public function format (string $ label ): string
168+ {
169+ $ label = 'FORMATTED: ' . trim ($ label );
170+
171+ return $ label ;
172+ }
173+ };
174+
175+ expect ($ anon ->format (' hello ' ))->toBe ('FORMATTED: hello ' )
176+ ->and ($ label )->toBe (42 )
177+ ;
178+ });
179+
180+ test ('still enforces local @var annotations declared inside anonymous class methods ' , function () {
181+ $ anon = new class () {
182+ public function compute (int $ multiplier ): int
183+ {
184+ /** @var positive-int $result */
185+ $ result = 10 * $ multiplier ;
186+
187+ return $ result ;
188+ }
189+ };
190+
191+ expect ($ anon ->compute (2 ))->toBe (20 );
192+
193+ expect (fn () => $ anon ->compute (-1 ))
194+ ->toThrow (TypeError::class, 'Variable $result must be of type positive-int ' )
195+ ;
196+ });
197+
198+ test ('arrow functions inside anonymous class methods capture method scope but do not leak to outer file ' , function () {
199+ /** @var positive-int $fileScoped */
200+ $ fileScoped = 50 ;
201+
202+ $ anon = new class () {
203+ public function execute (): void
204+ {
205+ /** @var non-empty-string $methodScoped */
206+ $ methodScoped = 'initial ' ;
207+
208+ $ badArrow = fn () => $ methodScoped = '' ;
209+ expect ($ badArrow )->toThrow (TypeError::class, 'Variable $methodScoped must be of type non-empty-string ' );
210+
211+ $ fileArrow = fn () => $ fileScoped = 'not_an_int_string ' ;
212+ expect ($ fileArrow ())->toBe ('not_an_int_string ' );
213+ }
214+ };
215+
216+ $ anon ->execute ();
217+ expect ($ fileScoped )->toBe (50 );
218+ });
219+
220+ test ('closures inside anonymous class methods without use clause do not inherit method variables ' , function () {
221+ $ anon = new class () {
222+ public function run (): string
223+ {
224+ /** @var positive-int $counter */
225+ $ counter = 10 ;
226+
227+ $ closure = function (): string {
228+ $ counter = 'counter_as_string ' ;
229+
230+ return $ counter ;
231+ };
232+
233+ return $ closure ();
234+ }
235+ };
236+
237+ expect ($ anon ->run ())->toBe ('counter_as_string ' );
238+ });
239+ });
142240});
0 commit comments