Skip to content

Commit a216927

Browse files
authored
Better static scope checks for \Drupal static calls (#581)
1 parent 78e5228 commit a216927

File tree

3 files changed

+23
-10
lines changed

3 files changed

+23
-10
lines changed

src/Rules/Drupal/GlobalDrupalDependencyInjectionRule.php

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44

55
use PhpParser\Node;
66
use PHPStan\Analyser\Scope;
7-
use PHPStan\Reflection\MethodReflection;
7+
use PHPStan\Reflection\ExtendedMethodReflection;
88
use PHPStan\Rules\Rule;
9-
use PHPStan\ShouldNotHappenException;
109

1110
class GlobalDrupalDependencyInjectionRule implements Rule
1211
{
@@ -23,7 +22,7 @@ public function processNode(Node $node, Scope $scope): array
2322
if (!($node->class instanceof Node\Name\FullyQualified) || (string) $node->class !== 'Drupal') {
2423
return [];
2524
}
26-
// Do not raise if called inside of a trait.
25+
// Do not raise if called inside a trait.
2726
if (!$scope->isInClass() || $scope->isInTrait()) {
2827
return [];
2928
}
@@ -60,15 +59,13 @@ public function processNode(Node $node, Scope $scope): array
6059
}
6160
}
6261

63-
if ($scope->getFunctionName() === null) {
64-
throw new ShouldNotHappenException();
65-
}
66-
6762
$scopeFunction = $scope->getFunction();
68-
if (!($scopeFunction instanceof MethodReflection)) {
69-
throw new ShouldNotHappenException();
63+
if ($scopeFunction === null) {
64+
return [];
65+
}
66+
if (!$scopeFunction instanceof ExtendedMethodReflection) {
67+
return [];
7068
}
71-
// Static methods have to invoke \Drupal.
7269
if ($scopeFunction->isStatic()) {
7370
return [];
7471
}

tests/src/Rules/GlobalDrupalDependencyInjectionRuleTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public function resultData(): \Generator
5858
[],
5959
];
6060

61+
yield [
62+
__DIR__ . '/data/bug-580.php',
63+
[],
64+
];
65+
6166
if (PHP_VERSION_ID >= 80100) {
6267
yield [
6368
__DIR__ . '/data/bug-500.php',

tests/src/Rules/data/bug-580.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Bug580;
4+
5+
class Foo {
6+
public function bar() {
7+
function baz() {
8+
\Drupal::a();
9+
}
10+
}
11+
}

0 commit comments

Comments
 (0)