Skip to content

Commit 93e1e21

Browse files
phpstan-botclaude
andcommitted
Add regression tests for phpstan/phpstan#3770 and phpstan/phpstan#6822
Both issues report that closures cannot be marked as impure via PHPDoc. These tests verify that @phpstan-impure on closures prevents incorrect type narrowing in conditional branches. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 2464761 commit 93e1e21

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug3770;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
// PHPDoc on closures should be respected for purity
8+
9+
/** @phpstan-impure */
10+
$f = static function (string $input): bool {
11+
return strlen($input) > rand(0, 10);
12+
};
13+
14+
if ($f('hello')) {
15+
// Should not narrow to true because closure is impure
16+
assertType('bool', $f('hello'));
17+
}
18+
19+
// Closure with @phpstan-pure should allow narrowing
20+
/** @phpstan-pure */
21+
$g = static function (string $input): bool {
22+
return strlen($input) > 5;
23+
};
24+
25+
if ($g('hello world')) {
26+
assertType('true', $g('hello world'));
27+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug6822;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
// Closures marked as @phpstan-impure should not have their return type narrowed
8+
9+
/** @phpstan-impure */
10+
$closure = function (): bool {
11+
return (bool) rand(0, 1);
12+
};
13+
14+
assertType('bool', $closure());
15+
16+
if ($closure()) {
17+
assertType('bool', $closure());
18+
}
19+
20+
// Same with an explicit impure closure assigned to a variable
21+
/** @phpstan-impure */
22+
$impureFn = function (): int {
23+
return rand(0, 100);
24+
};
25+
26+
if ($impureFn() > 50) {
27+
assertType('int<0, 100>', $impureFn());
28+
}

0 commit comments

Comments
 (0)