diff --git a/README.md b/README.md index bf2d5256..6c9fc252 100644 --- a/README.md +++ b/README.md @@ -208,11 +208,13 @@ parameters: pluginManagerSetsCacheBackendRule: false # Validates module_load_include() calls and loads the include for - # the rest of the analysis. + # the rest of the analysis. module_load_include() was removed in + # Drupal 11. moduleLoadInclude: false - # Validates ModuleHandlerInterface::loadInclude() calls and loads - # the include for the rest of the analysis. + # Reports ModuleHandlerInterface::loadInclude() calls whose module + # or file is missing. The include is loaded either way, so the + # functions it declares stay known. loadIncludes: false ``` diff --git a/extension.neon b/extension.neon index 9c33eaf2..01c79c34 100644 --- a/extension.neon +++ b/extension.neon @@ -366,6 +366,11 @@ services: class: mglaman\PHPStanDrupal\Type\EntityTypeId\EntityTypeIdTypeNodeResolverExtension tags: - phpstan.phpDoc.typeNodeResolverExtension + - + class: mglaman\PHPStanDrupal\Drupal\IncludeLoader + - + class: mglaman\PHPStanDrupal\Type\ModuleHandlerLoadIncludeReturnTypeExtension + tags: [phpstan.broker.dynamicMethodReturnTypeExtension] - class: mglaman\PHPStanDrupal\Type\EntityIdNarrowedByNew tags: [phpstan.broker.dynamicMethodReturnTypeExtension] diff --git a/src/Drupal/IncludeLoadResult.php b/src/Drupal/IncludeLoadResult.php new file mode 100644 index 00000000..95f6f66b --- /dev/null +++ b/src/Drupal/IncludeLoadResult.php @@ -0,0 +1,11 @@ + + */ + private array $results = []; + + public function __construct( + private readonly ExtensionMap $extensionMap + ) { + } + + /** + * Resolves the module and file name of a loadInclude() style call. + * + * @return array{string, string}|null + * The module name and the file name, or NULL when either isn't a + * constant string. + */ + public function resolve(Arg $module, Arg $type, ?Arg $name, Scope $scope): ?array + { + $moduleName = $this->getConstantString($module, $scope); + $fileType = $this->getConstantString($type, $scope); + if ($moduleName === null || $fileType === null) { + return null; + } + $baseName = $moduleName; + if ($name !== null) { + $baseName = $this->getConstantString($name, $scope); + if ($baseName === null) { + return null; + } + } + return [$moduleName, "$baseName.$fileType"]; + } + + /** + * @param Scope&DependencyTracker $scope + */ + public function load(string $moduleName, string $fileName, Scope $scope): IncludeLoadResult + { + $module = $this->extensionMap->getModule($moduleName); + if ($module === null) { + return IncludeLoadResult::ModuleNotFound; + } + $file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $fileName; + $scope->trackFileDependency($file); + if (!array_key_exists($file, $this->results)) { + $this->results[$file] = $this->require($file); + } + return $this->results[$file]; + } + + private function require(string $file): IncludeLoadResult + { + if (!is_file($file)) { + return IncludeLoadResult::FileNotFound; + } + try { + // Only the require itself is guarded: a broken include must not + // crash the analysis, but PHPStan's own exceptions elsewhere must + // propagate. + require_once $file; + } catch (ContainerNotInitializedException) { + // Top-level code in the include needs a container, which does not + // exist during analysis. Its top-level functions are still + // declared. + return IncludeLoadResult::Loaded; + } catch (Throwable) { + return IncludeLoadResult::NotLoadable; + } + return IncludeLoadResult::Loaded; + } + + private function getConstantString(Arg $arg, Scope $scope): ?string + { + $strings = $scope->getType($arg->value)->getConstantStrings(); + return count($strings) > 0 ? $strings[0]->getValue() : null; + } +} diff --git a/src/Rules/Drupal/LoadIncludeBase.php b/src/Rules/Drupal/LoadIncludeBase.php index 8a7c25f3..b94106a8 100644 --- a/src/Rules/Drupal/LoadIncludeBase.php +++ b/src/Rules/Drupal/LoadIncludeBase.php @@ -3,10 +3,9 @@ namespace mglaman\PHPStanDrupal\Rules\Drupal; use mglaman\PHPStanDrupal\Drupal\ExtensionMap; +use mglaman\PHPStanDrupal\Drupal\IncludeLoader; use PhpParser\Node; -use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; -use function count; /** * @template TNodeType of Node @@ -16,46 +15,13 @@ abstract class LoadIncludeBase implements Rule { public function __construct( - protected readonly ExtensionMap $extensionMap + protected readonly ExtensionMap $extensionMap, + protected readonly IncludeLoader $includeLoader ) { } - private function getStringArgValue(Node\Expr $expr, Scope $scope): ?string + protected function getModulePath(string $moduleName): string { - $type = $scope->getType($expr); - $stringTypes = $type->getConstantStrings(); - if (count($stringTypes) > 0) { - return $stringTypes[0]->getValue(); - } - return null; - } - - /** - * @return array{string, string}|array{false, false} - * The module name and file name, or [false, false] when either could - * not be resolved to a constant string. - */ - protected function parseLoadIncludeArgs(Node\Arg $module, Node\Arg $type, ?Node\Arg $name, Scope $scope): array - { - $moduleName = $this->getStringArgValue($module->value, $scope); - if ($moduleName === null) { - return [false, false]; - } - $fileType = $this->getStringArgValue($type->value, $scope); - if ($fileType === null) { - return [false, false]; - } - $baseName = null; - if ($name !== null) { - $baseName = $this->getStringArgValue($name->value, $scope); - if ($baseName === null) { - return [false, false]; - } - } - if ($baseName === null) { - $baseName = $moduleName; - } - - return [$moduleName, "$baseName.$fileType"]; + return $this->extensionMap->getModule($moduleName)?->getPath() ?? $moduleName; } } diff --git a/src/Rules/Drupal/LoadIncludes.php b/src/Rules/Drupal/LoadIncludes.php index 2db87d8f..dcfafda1 100644 --- a/src/Rules/Drupal/LoadIncludes.php +++ b/src/Rules/Drupal/LoadIncludes.php @@ -2,16 +2,14 @@ namespace mglaman\PHPStanDrupal\Rules\Drupal; -use Drupal\Core\DependencyInjection\ContainerNotInitializedException; use Drupal\Core\Extension\ModuleHandlerInterface; +use mglaman\PHPStanDrupal\Drupal\IncludeLoadResult; use PhpParser\Node; use PHPStan\Analyser\DependencyTracker; use PHPStan\Analyser\Scope; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\ObjectType; -use Throwable; use function count; -use function is_file; use function sprintf; /** @@ -47,63 +45,43 @@ public function processNode(Node $node, Scope $scope): array return []; } - // Try to invoke it similarly as the module handler itself. - [$moduleName, $filename] = $this->parseLoadIncludeArgs($args[0], $args[1], $args[2] ?? null, $scope); - if ($moduleName === false || $filename === false) { - // Couldn't determine module- nor file-name, most probably - // because it's a variable. Nothing to load, bail now. + $include = $this->includeLoader->resolve($args[0], $args[1], $args[2] ?? null, $scope); + if ($include === null) { + // Couldn't determine the module or file name, most probably + // because it's a variable. Nothing to load. return []; } - $module = $this->extensionMap->getModule($moduleName); - if ($module === null) { - return [ + [$moduleName, $filename] = $include; + + return match ($this->includeLoader->load($moduleName, $filename, $scope)) { + IncludeLoadResult::Loaded => [], + IncludeLoadResult::ModuleNotFound => [ RuleErrorBuilder::message(sprintf( 'File %s could not be loaded from %s::loadInclude because %s module is not found.', $filename, ModuleHandlerInterface::class, $moduleName )) - ->identifier('loadIncludes.moduleNotFound') - ->build() - ]; - } - - $file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $filename; - $scope->trackFileDependency($file); - if (is_file($file)) { - try { - // Load the include so its symbols are available for the rest - // of the analysis, mirroring what loadInclude() does at - // runtime. Only the require itself is guarded: a broken - // include must not crash the analysis, but PHPStan's own - // exceptions elsewhere must propagate. - require_once $file; - } catch (ContainerNotInitializedException $e) { - // Top-level code in the include needs a container, which does - // not exist during analysis. Its top-level functions are still - // declared. Reporting this would also be unreliable: PHP won't - // re-run the file, so only the first call in a process throws. - return []; - } catch (Throwable $e) { - return [ - RuleErrorBuilder::message(sprintf( - 'A file could not be loaded from %s::loadInclude', - ModuleHandlerInterface::class - )) + ->identifier('loadIncludes.moduleNotFound') + ->build(), + ], + IncludeLoadResult::NotLoadable => [ + RuleErrorBuilder::message(sprintf( + 'A file could not be loaded from %s::loadInclude', + ModuleHandlerInterface::class + )) ->identifier('loadIncludes.fileNotLoadable') - ->build() - ]; - } - return []; - } - return [ - RuleErrorBuilder::message(sprintf( - 'File %s could not be loaded from %s::loadInclude', - $module->getPath() . '/' . $filename, - ModuleHandlerInterface::class - )) - ->identifier('loadIncludes.fileNotLoadable') - ->build() - ]; + ->build(), + ], + IncludeLoadResult::FileNotFound => [ + RuleErrorBuilder::message(sprintf( + 'File %s could not be loaded from %s::loadInclude', + $this->getModulePath($moduleName) . '/' . $filename, + ModuleHandlerInterface::class + )) + ->identifier('loadIncludes.fileNotLoadable') + ->build(), + ], + }; } } diff --git a/src/Rules/Drupal/ModuleLoadInclude.php b/src/Rules/Drupal/ModuleLoadInclude.php index 5e27d01d..16903a5e 100644 --- a/src/Rules/Drupal/ModuleLoadInclude.php +++ b/src/Rules/Drupal/ModuleLoadInclude.php @@ -2,15 +2,13 @@ namespace mglaman\PHPStanDrupal\Rules\Drupal; -use Drupal\Core\DependencyInjection\ContainerNotInitializedException; +use mglaman\PHPStanDrupal\Drupal\IncludeLoadResult; use PhpParser\Node; use PhpParser\Node\Name; use PHPStan\Analyser\DependencyTracker; use PHPStan\Analyser\Scope; use PHPStan\Rules\RuleErrorBuilder; -use Throwable; use function count; -use function is_file; use function sprintf; /** @@ -46,57 +44,38 @@ public function processNode(Node $node, Scope $scope): array return []; } - // Try to invoke it similarly as the module handler itself. - [$moduleName, $filename] = $this->parseLoadIncludeArgs($args[1], $args[0], $args[2] ?? null, $scope); - if ($moduleName === false || $filename === false) { - // Couldn't determine module- nor file-name, most probably - // because it's a variable. Nothing to load, bail now. + $include = $this->includeLoader->resolve($args[1], $args[0], $args[2] ?? null, $scope); + if ($include === null) { + // Couldn't determine the module or file name, most probably + // because it's a variable. Nothing to load. return []; } - $module = $this->extensionMap->getModule($moduleName); - if ($module === null) { - return [ + [$moduleName, $filename] = $include; + + return match ($this->includeLoader->load($moduleName, $filename, $scope)) { + IncludeLoadResult::Loaded => [], + IncludeLoadResult::ModuleNotFound => [ RuleErrorBuilder::message(sprintf( 'File %s could not be loaded from module_load_include because %s module is not found.', $filename, $moduleName )) - ->identifier('moduleLoadInclude.moduleNotFound') - ->build() - ]; - } - $file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $filename; - $scope->trackFileDependency($file); - if (is_file($file)) { - try { - // Load the include so its symbols are available for the rest - // of the analysis, mirroring what module_load_include() does - // at runtime. Only the require itself is guarded: a broken - // include must not crash the analysis, but PHPStan's own - // exceptions elsewhere must propagate. - require_once $file; - } catch (ContainerNotInitializedException $e) { - // Top-level code in the include needs a container, which does - // not exist during analysis. Its top-level functions are still - // declared. Reporting this would also be unreliable: PHP won't - // re-run the file, so only the first call in a process throws. - return []; - } catch (Throwable $e) { - return [ - RuleErrorBuilder::message('A file could not be loaded from module_load_include') + ->identifier('moduleLoadInclude.moduleNotFound') + ->build(), + ], + IncludeLoadResult::NotLoadable => [ + RuleErrorBuilder::message('A file could not be loaded from module_load_include') ->identifier('moduleLoadInclude.moduleNotLoadable') - ->build() - ]; - } - return []; - } - return [ - RuleErrorBuilder::message(sprintf( - 'File %s could not be loaded from module_load_include.', - $module->getPath() . '/' . $filename - )) - ->identifier('moduleLoadInclude.moduleNotLoadable') - ->build() - ]; + ->build(), + ], + IncludeLoadResult::FileNotFound => [ + RuleErrorBuilder::message(sprintf( + 'File %s could not be loaded from module_load_include.', + $this->getModulePath($moduleName) . '/' . $filename + )) + ->identifier('moduleLoadInclude.moduleNotLoadable') + ->build(), + ], + }; } } diff --git a/src/Type/ModuleHandlerLoadIncludeReturnTypeExtension.php b/src/Type/ModuleHandlerLoadIncludeReturnTypeExtension.php new file mode 100644 index 00000000..3e36b293 --- /dev/null +++ b/src/Type/ModuleHandlerLoadIncludeReturnTypeExtension.php @@ -0,0 +1,62 @@ +getName() === 'loadInclude'; + } + + /** + * @param Scope&DependencyTracker $scope + */ + public function getTypeFromMethodCall( + MethodReflection $methodReflection, + MethodCall $methodCall, + Scope $scope + ): Type { + $args = $methodCall->getArgs(); + if (count($args) >= 2) { + $include = $this->includeLoader->resolve($args[0], $args[1], $args[2] ?? null, $scope); + if ($include !== null) { + $this->includeLoader->load($include[0], $include[1], $scope); + } + } + return ParametersAcceptorSelector::selectFromArgs( + $scope, + $args, + $methodReflection->getVariants() + )->getReturnType(); + } +} diff --git a/tests/fixtures/drupal/modules/phpstan_fixtures/phpstan_fixtures.loader.inc b/tests/fixtures/drupal/modules/phpstan_fixtures/phpstan_fixtures.loader.inc new file mode 100644 index 00000000..94dc0a63 --- /dev/null +++ b/tests/fixtures/drupal/modules/phpstan_fixtures/phpstan_fixtures.loader.inc @@ -0,0 +1,10 @@ +getByType(CallToNonExistentFunctionRule::class); + } + + public function testFunctionFromIncludeIsKnown(): void + { + $this->analyse([__DIR__ . '/data/load-include-without-rules.php'], []); + } +} diff --git a/tests/src/Rules/data/load-include-without-rules.php b/tests/src/Rules/data/load-include-without-rules.php new file mode 100644 index 00000000..e9932827 --- /dev/null +++ b/tests/src/Rules/data/load-include-without-rules.php @@ -0,0 +1,10 @@ +loadInclude('phpstan_fixtures', 'inc', 'phpstan_fixtures.loader'); + return phpstan_fixtures_function_from_load_include(); +}