Skip to content

Commit e7757dc

Browse files
phpstan-botondrejmirtes
authored andcommitted
Do not locate symbols declared by the symfony/polyfill-* packages bundled with PHPStan itself
* Added `SkipBundledPolyfillSourceLocator` which drops located functions, classes and constants whose file lives in a `symfony/polyfill-*` directory inside PHPStan's own installation directory (the source tree or the PHAR). * `BetterReflectionSourceLocatorFactory` wraps both runtime-based locators with it - `AutoloadFunctionsSourceLocator` and the `AutoloadSourceLocator` that answers from `function_exists()` / `class_exists()`. Polyfills installed in the analysed project keep working: the Composer source locators run before those two. * Classes have the same bug as the reported functions and are fixed by the same wrapper (e.g. `Filter\FilterException` from `symfony/polyfill-php85` was silently accepted with `phpVersion: 80400`). * Probed and left alone: global constants (PHPStan does not version-gate constants at all, even internal ones like `T_NAME_QUALIFIED`), `PhpInternalSourceLocator` and `EvaledCodeSourceLocator` (they only surface symbols that have an extension name, so userland polyfill declarations never reach them), and the attribute classes `NoDiscard`, `Deprecated`, `Override`, ... which better-reflection deliberately reports as present in every PHP version.
1 parent e1d6eb8 commit e7757dc

7 files changed

Lines changed: 237 additions & 3 deletions

File tree

‎.github/workflows/e2e-tests.yml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -804,6 +804,19 @@ jobs:
804804
/tmp/phpstan-install-1/bin/phpstan analyse -l 8 -vvv test.php
805805
mv /tmp/phpstan-install-1 /tmp/phpstan-install-2
806806
/tmp/phpstan-install-2/bin/phpstan analyse -l 8 -vvv test.php
807+
- script: |
808+
# PHPStan bundles symfony/polyfill-php85 for its own runtime, so array_first()
809+
# and other PHP 8.5 symbols are declared in the PHPStan process. A project
810+
# analysed with PHP 8.4 must not see them
811+
# (https://github.com/phpstan/phpstan/issues/15150).
812+
cd e2e/bug-15150
813+
OUTPUT=$(../bashunit -a exit_code "1" "../../bin/phpstan analyse --error-format=raw")
814+
echo "$OUTPUT"
815+
../bashunit -a contains 'test.php:11:Function array_first not found.' "$OUTPUT"
816+
../bashunit -a contains 'test.php:12:Function array_last not found.' "$OUTPUT"
817+
../bashunit -a contains 'test.php:21:Instantiated class Filter\FilterException not found.' "$OUTPUT"
818+
# array_find() exists in the analysed PHP version, PhpStorm stubs describe it
819+
../bashunit -a not_contains 'array_find' "$OUTPUT"
807820
808821
steps:
809822
- name: Harden the runner (Audit all outbound calls)

‎e2e/bug-15150/phpstan.dist.neon‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
parameters:
2+
level: 8
3+
phpVersion: 80400
4+
paths:
5+
- test.php

‎e2e/bug-15150/test.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15150;
4+
5+
/**
6+
* @param array<int, string> $a
7+
*/
8+
function doFoo(array $a): void
9+
{
10+
// PHP 8.5 functions, polyfilled by symfony/polyfill-php85 bundled with PHPStan
11+
echo array_first($a);
12+
echo array_last($a);
13+
14+
// PHP 8.4 function, available in the analysed PHP version
15+
echo array_find($a, static fn (string $v): bool => $v !== '') ?? '';
16+
}
17+
18+
function doBar(): void
19+
{
20+
// PHP 8.5 class, polyfilled by symfony/polyfill-php85 bundled with PHPStan
21+
throw new \Filter\FilterException('foo');
22+
}

‎src/Reflection/BetterReflection/BetterReflectionSourceLocatorFactory.php‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use PHPStan\Cache\Cache;
1616
use PHPStan\DependencyInjection\AutowiredParameter;
1717
use PHPStan\DependencyInjection\AutowiredService;
18+
use PHPStan\File\FileHelper;
1819
use PHPStan\Php\PhpVersion;
1920
use PHPStan\Reflection\BetterReflection\SourceLocator\AutoloadFunctionsSourceLocator;
2021
use PHPStan\Reflection\BetterReflection\SourceLocator\AutoloadSourceLocator;
@@ -28,6 +29,7 @@
2829
use PHPStan\Reflection\BetterReflection\SourceLocator\PhpVersionBlacklistSourceLocator;
2930
use PHPStan\Reflection\BetterReflection\SourceLocator\ReflectionClassSourceLocator;
3031
use PHPStan\Reflection\BetterReflection\SourceLocator\RewriteClassAliasSourceLocator;
32+
use PHPStan\Reflection\BetterReflection\SourceLocator\SkipBundledPolyfillSourceLocator;
3133
use PHPStan\Reflection\BetterReflection\SourceLocator\SkipClassAliasSourceLocator;
3234
use PHPStan\Reflection\BetterReflection\SourceLocator\SkipPolyfillSourceLocator;
3335
use PHPStan\Turbo\TurboExtensionEnabler;
@@ -56,6 +58,7 @@ public function __construct(
5658
#[AutowiredParameter(ref: '@php8PhpParser')]
5759
private Parser $php8Parser,
5860
private Cache $cache,
61+
private FileHelper $fileHelper,
5962
private PhpVersion $phpVersion,
6063
private PhpStormStubsSourceStubber $phpstormStubsSourceStubber,
6164
private ReflectionSourceStubber $reflectionSourceStubber,
@@ -98,13 +101,13 @@ public function create(): SourceLocator
98101
}
99102

100103
$astLocator = new Locator($this->parser);
101-
$locators[] = new AutoloadFunctionsSourceLocator(
104+
$locators[] = $this->skipBundledPolyfills(new AutoloadFunctionsSourceLocator(
102105
new AutoloadSourceLocator($this->fileNodesFetcher, false),
103106
new ReflectionClassSourceLocator(
104107
$astLocator,
105108
$this->reflectionSourceStubber,
106109
),
107-
);
110+
));
108111

109112
$analysedDirectories = [];
110113
$analysedFiles = [];
@@ -184,7 +187,7 @@ public function create(): SourceLocator
184187
$this->phpVersion,
185188
));
186189

187-
$locators[] = new AutoloadSourceLocator($this->fileNodesFetcher, true);
190+
$locators[] = $this->skipBundledPolyfills(new AutoloadSourceLocator($this->fileNodesFetcher, true));
188191
$locators[] = new PhpVersionBlacklistSourceLocator(new PhpInternalSourceLocator($astLocator, $this->reflectionSourceStubber), $this->phpstormStubsSourceStubber);
189192
$locators[] = new PhpVersionBlacklistSourceLocator(new EvaledCodeSourceLocator($astLocator, $this->reflectionSourceStubber), $this->phpstormStubsSourceStubber);
190193

@@ -196,4 +199,21 @@ public function create(): SourceLocator
196199
return new LazySourceLocator($initializer);
197200
}
198201

202+
/**
203+
* Symbols of the polyfills bundled with PHPStan are declared in the PHPStan process,
204+
* but they aren't part of the analysed project.
205+
*/
206+
private function skipBundledPolyfills(SourceLocator $sourceLocator): SourceLocator
207+
{
208+
$phpstanDirectories = [__DIR__ . '/../../..'];
209+
if (extension_loaded('phar')) {
210+
$pharProtocolPath = Phar::running();
211+
if ($pharProtocolPath !== '') {
212+
$phpstanDirectories[] = $pharProtocolPath;
213+
}
214+
}
215+
216+
return new SkipBundledPolyfillSourceLocator($sourceLocator, $this->fileHelper, $phpstanDirectories);
217+
}
218+
199219
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
4+
5+
use Override;
6+
use PHPStan\BetterReflection\Identifier\Identifier;
7+
use PHPStan\BetterReflection\Identifier\IdentifierType;
8+
use PHPStan\BetterReflection\Reflection\Reflection;
9+
use PHPStan\BetterReflection\Reflection\ReflectionClass;
10+
use PHPStan\BetterReflection\Reflection\ReflectionConstant;
11+
use PHPStan\BetterReflection\Reflection\ReflectionFunction;
12+
use PHPStan\BetterReflection\Reflector\Reflector;
13+
use PHPStan\BetterReflection\SourceLocator\Type\SourceLocator;
14+
use PHPStan\File\FileHelper;
15+
use function str_contains;
16+
use function str_starts_with;
17+
18+
/**
19+
* PHPStan bundles symfony/polyfill-* packages for its own runtime, so functions and classes like
20+
* array_first() or NoDiscard are declared in the PHPStan process even when the analysed project
21+
* knows nothing about them. Locators asking function_exists()/class_exists() would report them
22+
* as existing symbols of the analysed project.
23+
*
24+
* Polyfills installed in the analysed project are unaffected - they're located by the Composer
25+
* source locators which run before the runtime-based ones.
26+
*/
27+
final class SkipBundledPolyfillSourceLocator implements SourceLocator
28+
{
29+
30+
private const POLYFILL_PATH_PART = '/symfony/polyfill-';
31+
32+
/** @var string[] */
33+
private array $phpstanDirectories;
34+
35+
/** @param string[] $phpstanDirectories */
36+
public function __construct(
37+
private SourceLocator $sourceLocator,
38+
private FileHelper $fileHelper,
39+
array $phpstanDirectories,
40+
)
41+
{
42+
$normalized = [];
43+
foreach ($phpstanDirectories as $phpstanDirectory) {
44+
$normalized[] = $fileHelper->normalizePath($phpstanDirectory, '/') . '/';
45+
}
46+
47+
$this->phpstanDirectories = $normalized;
48+
}
49+
50+
#[Override]
51+
public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?Reflection
52+
{
53+
$reflection = $this->sourceLocator->locateIdentifier($reflector, $identifier);
54+
if ($reflection === null) {
55+
return null;
56+
}
57+
58+
if ($reflection instanceof ReflectionClass || $reflection instanceof ReflectionFunction || $reflection instanceof ReflectionConstant) {
59+
$fileName = $reflection->getFileName();
60+
if ($fileName !== null && $this->isBundledPolyfillFile($fileName)) {
61+
return null;
62+
}
63+
}
64+
65+
return $reflection;
66+
}
67+
68+
#[Override]
69+
public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array
70+
{
71+
return $this->sourceLocator->locateIdentifiersByType($reflector, $identifierType);
72+
}
73+
74+
private function isBundledPolyfillFile(string $fileName): bool
75+
{
76+
$normalized = $this->fileHelper->normalizePath($fileName, '/');
77+
if (!str_contains($normalized, self::POLYFILL_PATH_PART)) {
78+
return false;
79+
}
80+
81+
foreach ($this->phpstanDirectories as $phpstanDirectory) {
82+
if (str_starts_with($normalized, $phpstanDirectory)) {
83+
return true;
84+
}
85+
}
86+
87+
return false;
88+
}
89+
90+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
4+
5+
use PHPStan\BetterReflection\Reflector\DefaultReflector;
6+
use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound;
7+
use PHPStan\BetterReflection\Reflector\Reflector;
8+
use PHPStan\Reflection\BetterReflection\BetterReflectionSourceLocatorFactory;
9+
use PHPStan\Testing\PHPStanTestCase;
10+
use PHPUnit\Framework\Attributes\DataProvider;
11+
use PHPUnit\Framework\Attributes\RequiresPhp;
12+
use function sprintf;
13+
14+
class SkipBundledPolyfillSourceLocatorTest extends PHPStanTestCase
15+
{
16+
17+
public static function getAdditionalConfigFiles(): array
18+
{
19+
return [__DIR__ . '/data/php-8.4.neon'];
20+
}
21+
22+
/** @return iterable<string, array{string}> */
23+
public static function dataPolyfilledFunctions(): iterable
24+
{
25+
yield 'array_first' => ['array_first'];
26+
yield 'array_last' => ['array_last'];
27+
yield 'get_error_handler' => ['get_error_handler'];
28+
}
29+
30+
/**
31+
* PHP 8.5 functions are declared in the PHPStan process by symfony/polyfill-php85,
32+
* but they don't exist in a project analysed with PHP 8.4.
33+
*/
34+
#[DataProvider('dataPolyfilledFunctions')]
35+
public function testFunctionFromBundledPolyfillIsNotFound(string $functionName): void
36+
{
37+
$reflector = $this->createReflector();
38+
39+
try {
40+
$reflection = $reflector->reflectFunction($functionName);
41+
} catch (IdentifierNotFound) {
42+
$this->expectNotToPerformAssertions();
43+
return;
44+
}
45+
46+
$this->fail(sprintf('Function %s() should not be found, it is declared in %s.', $functionName, $reflection->getFileName() ?? 'an unknown file'));
47+
}
48+
49+
/**
50+
* On PHP 8.5 the class is a real internal class of the running PHP version,
51+
* symfony/polyfill-php85 declares nothing.
52+
*/
53+
#[RequiresPhp('<8.5')]
54+
public function testClassFromBundledPolyfillIsNotFound(): void
55+
{
56+
$reflector = $this->createReflector();
57+
58+
try {
59+
$reflection = $reflector->reflectClass('Filter\FilterException');
60+
} catch (IdentifierNotFound) {
61+
$this->expectNotToPerformAssertions();
62+
return;
63+
}
64+
65+
$this->fail(sprintf('Class Filter\FilterException should not be found, it is declared in %s.', $reflection->getFileName() ?? 'an unknown file'));
66+
}
67+
68+
public function testOtherRuntimeSymbolsAreStillFound(): void
69+
{
70+
$reflector = $this->createReflector();
71+
72+
$this->assertSame(self::class, $reflector->reflectClass(self::class)->getName());
73+
}
74+
75+
private function createReflector(): Reflector
76+
{
77+
$factory = self::getContainer()->getByType(BetterReflectionSourceLocatorFactory::class);
78+
79+
return new DefaultReflector($factory->create());
80+
}
81+
82+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
parameters:
2+
phpVersion: 80400

0 commit comments

Comments
 (0)