Skip to content

Commit feeebeb

Browse files
committed
Invalidate the result cache when attribute services change
Classes registered from attributeServicesDirectories are services, so a change in them can affect the analysis of every file. AutowiredAttributeServicesExtension stores the registered discovered classes in the attributeServicesClasses parameter. ResultCacheManager treats them like the classes from the services section: editing one of them, or one of their dependencies, invalidates the result cache. Other classes in the same directories do not. A Composer update of a package owning one of the directories invalidates the whole result cache, like it does for packages with services in the config. PackageDependencyResolver::resolveDirectoryPackage() also matches a directory that is a package's install path. Amp-Thread-ID: https://ampcode.com/threads/T-01a19cd4-be31-75b4-bd15-67786eff5983
1 parent df96878 commit feeebeb

16 files changed

Lines changed: 192 additions & 33 deletions

File tree

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1668,6 +1668,24 @@ jobs:
16681668
../bashunit assert contains 'Result cache not used because extension file' "$OUTPUT"
16691669
../bashunit assert contains 'the rule says another thing' "$OUTPUT"
16701670
../bashunit assert not_contains 'the rule says one thing' "$OUTPUT"
1671+
- script: |
1672+
cd e2e/result-cache-extension-attribute-services
1673+
composer install
1674+
# The rule is registered through the attributeServicesDirectories section, not in services:.
1675+
# Editing it has to invalidate the cache, editing another class in the same directory does not.
1676+
OUTPUT=$(../bashunit assert exit_code "1" "../../bin/phpstan analyse -vv --error-format raw")
1677+
echo "$OUTPUT"
1678+
../bashunit assert contains 'the rule says one thing' "$OUTPUT"
1679+
patch -p0 < foo.patch
1680+
OUTPUT=$(../bashunit assert exit_code "1" "../../bin/phpstan analyse -vv --error-format raw")
1681+
echo "$OUTPUT"
1682+
../bashunit assert contains 'Result cache restored. 1 file will be reanalysed.' "$OUTPUT"
1683+
patch -p0 < rule.patch
1684+
OUTPUT=$(../bashunit assert exit_code "1" "../../bin/phpstan analyse -vv --error-format raw")
1685+
echo "$OUTPUT"
1686+
../bashunit assert contains 'Result cache not used because extension file' "$OUTPUT"
1687+
../bashunit assert contains 'the rule says another thing' "$OUTPUT"
1688+
../bashunit assert not_contains 'the rule says one thing' "$OUTPUT"
16711689
- script: |
16721690
cd e2e/result-cache-extension-copied-package
16731691
composer install

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ parametersSchema:
219219
usedLevel: string()
220220
cliAutoloadFile: schema(string(), nullable())
221221
attributeServicesDirectories: listOf(string())
222+
attributeServicesClasses: listOf(string())
222223

223224
# internal - editor mode
224225
singleReflectionFile: schema(string(), nullable())
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/vendor
2+
/composer.lock
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"name": "phpstan/result-cache-extension-attribute-services-e2e",
3+
"autoload": {
4+
"psr-4": {
5+
"ResultCacheE2EAttributeServices\\": "src/"
6+
}
7+
}
8+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
attributeServicesDirectories:
2+
- src
3+
4+
parameters:
5+
level: 0
6+
tmpDir: tmp
7+
paths:
8+
- src
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace ResultCacheE2EAttributeServices;
4+
5+
class Foo
6+
{
7+
8+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
*
2+
!.*

‎src/Analyser/ResultCache/ResultCacheManager.php‎

Lines changed: 42 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,8 @@ final class ResultCacheManager
187187
* @param string[] $analysedPaths
188188
* @param string[] $analysedPathsFromConfig
189189
* @param string[] $composerAutoloaderProjectPaths
190+
* @param string[] $attributeServicesDirectories
191+
* @param list<string> $attributeServicesClasses classes registered from attributeServicesDirectories
190192
* @param string[] $bootstrapFiles
191193
* @param string[] $scanFiles
192194
* @param string[] $scanDirectories
@@ -213,6 +215,10 @@ public function __construct(
213215
#[AutowiredParameter]
214216
private array $composerAutoloaderProjectPaths,
215217
#[AutowiredParameter]
218+
private array $attributeServicesDirectories,
219+
#[AutowiredParameter]
220+
private array $attributeServicesClasses,
221+
#[AutowiredParameter]
216222
private string $usedLevel,
217223
#[AutowiredParameter]
218224
private ?string $cliAutoloadFile,
@@ -2805,6 +2811,15 @@ private function readFrame($handle, int $length): mixed
28052811
*/
28062812
private function changedPackagesProvideContainerClass(?array $projectConfig, array $changedPackagesLookup): bool
28072813
{
2814+
// Directories from the attributeServicesDirectories section register services straight from
2815+
// their classes, so a changed package owning one of them can affect the analysis of every file.
2816+
foreach ($this->attributeServicesDirectories as $attributeServicesDirectory) {
2817+
$package = $this->packageDependencyResolver->resolveDirectoryPackage($attributeServicesDirectory);
2818+
if ($package !== null && array_key_exists($package, $changedPackagesLookup)) {
2819+
return true;
2820+
}
2821+
}
2822+
28082823
// Extensions registered directly in the project config (services:/rules:) or via an included
28092824
// extension neon file: resolve each service class to the package that owns its file.
28102825
if ($projectConfig !== null) {
@@ -2849,42 +2864,43 @@ private function getProjectExtensionFiles(?array $projectConfig, array $dependen
28492864
{
28502865
$this->alreadyProcessed = [];
28512866
$projectExtensionFiles = [];
2867+
$classes = $this->attributeServicesClasses;
28522868
if ($projectConfig !== null) {
2853-
$classes = ProjectConfigHelper::getServiceClassNames($projectConfig);
2854-
foreach ($classes as $class) {
2855-
try {
2856-
// does not use static reflection to reduce file-parsing
2857-
$classReflection = new ReflectionClass($class); /** @phpstan-ignore argument.type */
2858-
} catch (ReflectionException) {
2859-
continue;
2860-
}
2869+
$classes = array_merge(ProjectConfigHelper::getServiceClassNames($projectConfig), $classes);
2870+
}
2871+
foreach ($classes as $class) {
2872+
try {
2873+
// does not use static reflection to reduce file-parsing
2874+
$classReflection = new ReflectionClass($class); /** @phpstan-ignore argument.type */
2875+
} catch (ReflectionException) {
2876+
continue;
2877+
}
28612878

2862-
$fileName = $classReflection->getFileName();
2863-
if ($fileName === false) {
2864-
continue;
2865-
}
2879+
$fileName = $classReflection->getFileName();
2880+
if ($fileName === false) {
2881+
continue;
2882+
}
28662883

2867-
if (str_starts_with($fileName, 'phar://')) {
2884+
if (str_starts_with($fileName, 'phar://')) {
2885+
continue;
2886+
}
2887+
2888+
$allServiceFiles = $this->getAllDependencies($fileName, $dependencies);
2889+
if (count($allServiceFiles) === 0) {
2890+
if ($this->packageDependencyResolver->isFileOfInstalledPackage($fileName)) {
28682891
continue;
28692892
}
28702893

2871-
$allServiceFiles = $this->getAllDependencies($fileName, $dependencies);
2872-
if (count($allServiceFiles) === 0) {
2873-
if ($this->packageDependencyResolver->isFileOfInstalledPackage($fileName)) {
2874-
continue;
2875-
}
2894+
$projectExtensionFiles[$fileName] = [$this->getFileHash($fileName), false, $class];
2895+
continue;
2896+
}
28762897

2877-
$projectExtensionFiles[$fileName] = [$this->getFileHash($fileName), false, $class];
2898+
foreach ($allServiceFiles as $serviceFile) {
2899+
if (array_key_exists($serviceFile, $projectExtensionFiles)) {
28782900
continue;
28792901
}
28802902

2881-
foreach ($allServiceFiles as $serviceFile) {
2882-
if (array_key_exists($serviceFile, $projectExtensionFiles)) {
2883-
continue;
2884-
}
2885-
2886-
$projectExtensionFiles[$serviceFile] = [$this->getFileHash($serviceFile), true, $class];
2887-
}
2903+
$projectExtensionFiles[$serviceFile] = [$this->getFileHash($serviceFile), true, $class];
28882904
}
28892905
}
28902906

‎src/Dependency/PackageDependencyResolver.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
use function is_file;
2121
use function is_string;
2222
use function realpath;
23+
use function rtrim;
2324
use function str_starts_with;
2425
use function strlen;
2526
use function strtolower;
@@ -113,6 +114,21 @@ public function isFileOfInstalledPackage(string $file): bool
113114
return false;
114115
}
115116

117+
/**
118+
* Unlike resolvePackage(), also matches a directory that IS a package's install path.
119+
*/
120+
public function resolveDirectoryPackage(string $directory): ?string
121+
{
122+
$normalizedDirectory = rtrim($this->fileHelper->normalizePath($directory, '/'), '/');
123+
foreach ($this->getInstallPathToPackage() as $installPath => $package) {
124+
if ($normalizedDirectory === $installPath || str_starts_with($normalizedDirectory, $installPath . '/')) {
125+
return $package;
126+
}
127+
}
128+
129+
return null;
130+
}
131+
116132
private function doResolvePackage(string $file): ?string
117133
{
118134
// Normalize with a forward slash regardless of platform: normalizePath() defaults to

‎src/DependencyInjection/AttributeServices/AttributeServicesRegistrar.php‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,12 @@
4848
final class AttributeServicesRegistrar
4949
{
5050

51-
public static function registerServices(ContainerBuilder $builder, AttributeTargetsProvider $targets, ?int $level): void
51+
/**
52+
* @return list<class-string> the registered classes
53+
*/
54+
public static function registerServices(ContainerBuilder $builder, AttributeTargetsProvider $targets, ?int $level): array
5255
{
56+
$registeredClasses = [];
5357
$constructorParameters = self::collectConstructorParameters($targets);
5458

5559
$conditionalTargets = [];
@@ -73,6 +77,7 @@ public static function registerServices(ContainerBuilder $builder, AttributeTarg
7377
$definition->setFactory(new Statement([new Reference(substr($ref, 1)), $method]));
7478
}
7579

80+
$registeredClasses[] = $class->name;
7681
self::processConstructorParameters($builder, $class->name, $definition, $constructorParameters);
7782

7883
if (!$attribute->autoTag || !$tagged) {
@@ -100,6 +105,7 @@ public static function registerServices(ContainerBuilder $builder, AttributeTarg
100105
$definition->setFactory(new Statement([new Reference(substr($ref, 1)), $method]));
101106
}
102107

108+
$registeredClasses[] = $class->name;
103109
self::processConstructorParameters($builder, $class->name, $definition, $constructorParameters);
104110
}
105111

@@ -113,11 +119,12 @@ public static function registerServices(ContainerBuilder $builder, AttributeTarg
113119
}
114120

115121
$resultDefinition = $definition->getResultDefinition();
122+
$registeredClasses[] = $class->name;
116123
self::processConstructorParameters($builder, $class->name, $resultDefinition, $constructorParameters);
117124
}
118125

119126
if ($level === null) {
120-
return;
127+
return $registeredClasses;
121128
}
122129

123130
foreach (self::findTargetClasses($targets, RegisteredRule::class, $conditionalTargets) as [$class, $tagged]) {
@@ -133,6 +140,7 @@ public static function registerServices(ContainerBuilder $builder, AttributeTarg
133140
$definition->addTag(LazyRegistry::RULE_TAG);
134141
}
135142

143+
$registeredClasses[] = $class->name;
136144
self::processConstructorParameters($builder, $class->name, $definition, $constructorParameters);
137145
}
138146

@@ -149,8 +157,11 @@ public static function registerServices(ContainerBuilder $builder, AttributeTarg
149157
$definition->addTag(RegistryFactory::COLLECTOR_TAG);
150158
}
151159

160+
$registeredClasses[] = $class->name;
152161
self::processConstructorParameters($builder, $class->name, $definition, $constructorParameters);
153162
}
163+
164+
return $registeredClasses;
154165
}
155166

156167
/**

0 commit comments

Comments
 (0)