Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down
5 changes: 5 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
11 changes: 11 additions & 0 deletions src/Drupal/IncludeLoadResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php declare(strict_types=1);

namespace mglaman\PHPStanDrupal\Drupal;

enum IncludeLoadResult
{
case Loaded;
case ModuleNotFound;
case FileNotFound;
case NotLoadable;
}
106 changes: 106 additions & 0 deletions src/Drupal/IncludeLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php declare(strict_types=1);

namespace mglaman\PHPStanDrupal\Drupal;

use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
use PhpParser\Node\Arg;
use PHPStan\Analyser\DependencyTracker;
use PHPStan\Analyser\Scope;
use Throwable;
use function array_key_exists;
use function count;
use function is_file;
use const DIRECTORY_SEPARATOR;

/**
* Loads module include files so the functions they declare are known.
*
* ModuleHandlerInterface::loadInclude() and module_load_include() load a
* file at runtime. Analysis does the same, so calls to the functions in that
* file resolve. The return type extension loads the file whenever the call is
* analyzed. The rules report a missing module or file.
*
* Each file is loaded once, and the result is kept: PHP won't run a file
* twice, so a later caller must get the same result as the first one.
*/
final class IncludeLoader
{

/**
* @var array<string, IncludeLoadResult>
*/
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;
}
}
44 changes: 5 additions & 39 deletions src/Rules/Drupal/LoadIncludeBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}
}
82 changes: 30 additions & 52 deletions src/Rules/Drupal/LoadIncludes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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(),
],
};
}
}
Loading
Loading