Skip to content

Commit e758aec

Browse files
SanderMullerclaude
andcommitted
Narrow the container cache key to the referenced %env.* variables
PHPStan puts the whole environment into the DI container cache key, so any unrelated env change (CI, shell session, etc.) forces a full container recompile (phpstan/phpstan#14072). Keep env a static parameter and narrow only the cache key to the %env.*% variables the loaded configs actually reference, plus the env vars read at build time by CompilerExtensions (BUILD_TIME_ENV_VARIABLES). The full environment stays in the container parameters, so %env.*% resolution and the compiled container are unchanged. References are enumerated from the config as parsed by PHPStan's own NeonAdapter - the same parser the container compiler uses - not from raw config text: comments are ignored, and service entities become Statements so a %env.NAME% in a parameter value, a service argument or a factory is found the same way it is at compile time. The %env.NAME% grammar mirrors Nette's parameter-name grammar, so dashed names like %env.MY-VAR% are handled. A bare %env% reference, or a config that can't be parsed here, keeps the full environment in the key. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 709654e commit e758aec

8 files changed

Lines changed: 429 additions & 0 deletions

‎src/DependencyInjection/Configurator.php‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,36 @@
66
use Nette\DI\Config\Loader;
77
use Nette\DI\Container as OriginalNetteContainer;
88
use Nette\DI\ContainerLoader;
9+
use Nette\DI\Definitions\Statement;
10+
use Nette\Neon\Entity;
911
use Override;
1012
use PHPStan\File\CouldNotReadFileException;
1113
use PHPStan\File\CouldNotWriteFileException;
1214
use PHPStan\File\FileReader;
1315
use PHPStan\File\FileWriter;
1416
use PHPStan\Turbo\TurboExtensionEnabler;
17+
use Throwable;
18+
use function array_fill_keys;
19+
use function array_intersect_key;
1520
use function array_keys;
1621
use function count;
1722
use function error_reporting;
1823
use function explode;
24+
use function file_get_contents;
1925
use function hash_file;
2026
use function implode;
2127
use function in_array;
28+
use function is_array;
2229
use function is_dir;
2330
use function is_file;
31+
use function is_string;
2432
use function ksort;
33+
use function preg_match;
34+
use function preg_match_all;
2535
use function restore_error_handler;
2636
use function set_error_handler;
2737
use function sprintf;
38+
use function str_contains;
2839
use function str_ends_with;
2940
use function substr;
3041
use function time;
@@ -38,6 +49,13 @@
3849
final class Configurator extends \Nette\Bootstrap\Configurator
3950
{
4051

52+
/**
53+
* Env vars PHPStan reads at build time in a CompilerExtension (FnsrExtension reads PHPSTAN_FNSR),
54+
* so the container depends on them and they must stay in the cache key. ContainerCacheKeyEnvGuardTest
55+
* fails if a CompilerExtension reads an env var not listed here or referenced via %env.*%.
56+
*/
57+
public const BUILD_TIME_ENV_VARIABLES = ['PHPSTAN_FNSR'];
58+
4159
/** @var string[] */
4260
private array $allConfigFiles = [];
4361

@@ -97,6 +115,19 @@ public function loadContainer(): string
97115
// make sure invocations via blackfire use the same container
98116
unset($staticParameters['env']['BLACKFIRE_AGENT_SOCKET']);
99117

118+
// Keep only the env vars the container actually depends on in the cache key, so unrelated env
119+
// changes (CI/shell) don't force a full recompile - phpstan/phpstan#14072. The full env stays
120+
// in the container parameters, so %env.*% resolution is unaffected; this only narrows the key.
121+
if (isset($staticParameters['env'])) {
122+
$relevantEnvVariableNames = $this->relevantEnvVariableNamesForCacheKey();
123+
if ($relevantEnvVariableNames !== null) {
124+
$staticParameters['env'] = array_intersect_key(
125+
$staticParameters['env'],
126+
array_fill_keys($relevantEnvVariableNames, true),
127+
);
128+
}
129+
}
130+
100131
$containerKey = [
101132
$staticParameters,
102133
array_keys($this->dynamicParameters),
@@ -231,6 +262,96 @@ public function createContainer(bool $initialize = true): OriginalNetteContainer
231262
return $container;
232263
}
233264

265+
/**
266+
* Env vars that can change the generated container, so they must stay in the cache key: every
267+
* %env.NAME% referenced across the loaded configs, plus BUILD_TIME_ENV_VARIABLES. Returns null
268+
* when a config references the whole %env% array (or its references can't be safely enumerated),
269+
* in which case all of it must be kept.
270+
*
271+
* References are enumerated from the config as parsed by PHPStan's own NeonAdapter - the same
272+
* parser the container compiler uses - rather than from raw config text: comments are ignored and
273+
* service entities become Statements, so a %env.NAME% in a parameter value, a service argument or
274+
* a factory is found the same way it is at compile time. The %env.NAME% grammar mirrors Nette's
275+
* parameter-name grammar (%([\w.-]*)%), so dashed names like %env.MY-VAR% are handled too.
276+
*
277+
* @return list<string>|null
278+
*/
279+
private function relevantEnvVariableNamesForCacheKey(): ?array
280+
{
281+
$names = self::BUILD_TIME_ENV_VARIABLES;
282+
$adapter = new NeonAdapter([]);
283+
284+
foreach ($this->allConfigFiles as $file) {
285+
$contents = @file_get_contents($file);
286+
if ($contents === false || !str_contains($contents, '%env')) {
287+
continue;
288+
}
289+
290+
try {
291+
$data = $adapter->load($file);
292+
} catch (Throwable) {
293+
// A config we can't parse as NEON here (e.g. a .php config) might reference any env
294+
// var, so we can't prove which ones the container needs: keep the whole environment.
295+
return null;
296+
}
297+
298+
$referencesWholeEnv = false;
299+
$referencedNames = $this->collectReferencedEnvVariableNames($data, $referencesWholeEnv);
300+
if ($referencesWholeEnv) {
301+
return null;
302+
}
303+
304+
foreach ($referencedNames as $name) {
305+
$names[] = $name;
306+
}
307+
}
308+
309+
return $names;
310+
}
311+
312+
/**
313+
* Recursively collect the env-variable names referenced by %env.NAME% in a parsed config node.
314+
* Recurses into arrays and into the service definitions the NeonAdapter produces (Statements, and
315+
* any remaining Neon entities) so references in service arguments and factories are not missed.
316+
* Sets $referencesWholeEnv on a bare %env% (the whole environment), which forces keeping all of it.
317+
*
318+
* @param mixed $node
319+
* @return list<string>
320+
*/
321+
private function collectReferencedEnvVariableNames($node, bool &$referencesWholeEnv): array
322+
{
323+
if (is_string($node)) {
324+
if (preg_match('~%env%~', $node) === 1) {
325+
$referencesWholeEnv = true;
326+
}
327+
328+
if (preg_match_all('~%env\.([\w.-]+)%~', $node, $matches) > 0) {
329+
return $matches[1];
330+
}
331+
332+
return [];
333+
}
334+
335+
if ($node instanceof Statement) {
336+
$node = [$node->getEntity(), $node->arguments];
337+
} elseif ($node instanceof Entity) {
338+
$node = [$node->value, $node->attributes];
339+
}
340+
341+
if (!is_array($node)) {
342+
return [];
343+
}
344+
345+
$names = [];
346+
foreach ($node as $value) {
347+
foreach ($this->collectReferencedEnvVariableNames($value, $referencesWholeEnv) as $name) {
348+
$names[] = $name;
349+
}
350+
}
351+
352+
return $names;
353+
}
354+
234355
/**
235356
* @return string[]
236357
*/
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\DependencyInjection;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use RecursiveDirectoryIterator;
7+
use RecursiveIteratorIterator;
8+
use SplFileInfo;
9+
use function file_get_contents;
10+
use function implode;
11+
use function in_array;
12+
use function preg_match_all;
13+
use function sort;
14+
use function str_contains;
15+
use const PHP_EOL;
16+
17+
/**
18+
* Guards the container-cache-key narrowing in Configurator (phpstan/phpstan#14072): when no config
19+
* references %env.*%, env vars are dropped from the cache key, so any env var a CompilerExtension
20+
* reads at *build time* (getenv()/$_ENV) must be declared in Configurator::BUILD_TIME_ENV_VARIABLES -
21+
* otherwise changing it would silently reuse a stale container. A new build-time env read in any
22+
* extension fails this test instead of re-opening that hole. Detection is intentionally simple, with
23+
* documented limits (acceptable - PHPStan's build-time env access goes through these patterns):
24+
* literal env-var names only (route dynamic ones via %env.*), getenv()/$_ENV reads (not $_SERVER),
25+
* and classes that directly extend CompilerExtension (not env read in a helper they delegate to).
26+
*/
27+
final class ContainerCacheKeyEnvGuardTest extends TestCase
28+
{
29+
30+
public function testBuildTimeEnvReadsInCompilerExtensionsAreDeclared(): void
31+
{
32+
$srcDir = __DIR__ . '/../../../src';
33+
$offenders = [];
34+
35+
/** @var SplFileInfo $file */
36+
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($srcDir, RecursiveDirectoryIterator::SKIP_DOTS)) as $file) {
37+
if (!$file->isFile() || $file->getExtension() !== 'php') {
38+
continue;
39+
}
40+
41+
$contents = file_get_contents($file->getPathname());
42+
if ($contents === false || !str_contains($contents, 'extends CompilerExtension')) {
43+
continue;
44+
}
45+
46+
if (preg_match_all('~(?:getenv\(|\$_ENV\[)\s*[\'"]([A-Za-z_][A-Za-z0-9_]*)[\'"]~', $contents, $matches) === 0) {
47+
continue;
48+
}
49+
50+
foreach ($matches[1] as $envName) {
51+
if (in_array($envName, Configurator::BUILD_TIME_ENV_VARIABLES, true)) {
52+
continue;
53+
}
54+
55+
$offenders[] = $file->getFilename() . ': ' . $envName;
56+
}
57+
}
58+
59+
sort($offenders);
60+
61+
$this->assertSame(
62+
[],
63+
$offenders,
64+
'A CompilerExtension reads an environment variable at build time that is not declared in '
65+
. 'Configurator::BUILD_TIME_ENV_VARIABLES. Add it there (so it stays in the container cache '
66+
. 'key and a change recompiles), or read it via %env.* in a config instead:' . PHP_EOL
67+
. implode(PHP_EOL, $offenders),
68+
);
69+
}
70+
71+
}

0 commit comments

Comments
 (0)