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
64 changes: 64 additions & 0 deletions src/Node/ClassConstantsNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\NodeAbstract;
use PHPStan\Node\Constant\ClassConstantFetch;
use PHPStan\Node\Constant\PhpDocClassConstantReference;
use PHPStan\Reflection\ClassReflection;

/**
Expand All @@ -15,6 +16,9 @@
final class ClassConstantsNode extends NodeAbstract implements VirtualNode
{

/** @var PhpDocClassConstantReference[]|null */
private ?array $phpDocFetches = null;

/**
* @param ClassConst[] $constants
* @param ClassConstantFetch[] $fetches
Expand Down Expand Up @@ -45,6 +49,66 @@ public function getFetches(): array
return $this->fetches;
}

/**
* @return PhpDocClassConstantReference[]
*/
public function getPhpDocFetches(): array
{
if ($this->phpDocFetches !== null) {
return $this->phpDocFetches;
}

$result = [];
$className = $this->classReflection->getName();

$resolvedPhpDoc = $this->classReflection->getResolvedPhpDoc();
if ($resolvedPhpDoc !== null) {
foreach ($resolvedPhpDoc->getClassConstantReferences() as $reference) {
$result[] = $reference;
}
}

foreach ($this->classReflection->getNativeReflection()->getMethods() as $method) {
if ($method->getDeclaringClass()->getName() !== $className) {
continue;
}
if (!$this->classReflection->hasNativeMethod($method->getName())) {
continue;
}
$methodReflection = $this->classReflection->getNativeMethod($method->getName());
$methodPhpDoc = $methodReflection->getResolvedPhpDoc();
if ($methodPhpDoc === null) {
continue;
}

foreach ($methodPhpDoc->getClassConstantReferences() as $reference) {
$result[] = $reference;
}
}

foreach ($this->classReflection->getNativeReflection()->getProperties() as $property) {
if ($property->getDeclaringClass()->getName() !== $className) {
continue;
}
if (!$this->classReflection->hasNativeProperty($property->getName())) {
continue;
}
$propertyReflection = $this->classReflection->getNativeProperty($property->getName());
$propertyPhpDoc = $propertyReflection->getResolvedPhpDoc();
if ($propertyPhpDoc === null) {
continue;
}

foreach ($propertyPhpDoc->getClassConstantReferences() as $reference) {
$result[] = $reference;
}
}

$this->phpDocFetches = $result;

return $result;
}

#[Override]
public function getType(): string
{
Expand Down
22 changes: 22 additions & 0 deletions src/Node/Constant/PhpDocClassConstantReference.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php declare(strict_types = 1);

namespace PHPStan\Node\Constant;

final class PhpDocClassConstantReference
{

public function __construct(private string $className, private string $constantName)
{
}

public function getClassName(): string
{
return $this->className;
}

public function getConstantName(): string
{
return $this->constantName;
}

}
71 changes: 71 additions & 0 deletions src/PhpDoc/ResolvedPhpDocBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPStan\PhpDoc;

use PHPStan\Analyser\NameScope;
use PHPStan\Node\Constant\PhpDocClassConstantReference;
use PHPStan\PhpDoc\Tag\AssertTag;
use PHPStan\PhpDoc\Tag\DeprecatedTag;
use PHPStan\PhpDoc\Tag\ExtendsTag;
Expand All @@ -25,6 +26,8 @@
use PHPStan\PhpDoc\Tag\TypedTag;
use PHPStan\PhpDoc\Tag\UsesTag;
use PHPStan\PhpDoc\Tag\VarTag;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
use PHPStan\PhpDocParser\Ast\Node as PhpDocAstNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
Expand All @@ -38,7 +41,11 @@
use function array_key_exists;
use function array_map;
use function count;
use function get_object_vars;
use function in_array;
use function is_array;
use function is_bool;
use function strtolower;
use function substr;

/**
Expand Down Expand Up @@ -153,6 +160,9 @@ final class ResolvedPhpDocBlock

private ?bool $acceptsNamedArguments = null;

/** @var PhpDocClassConstantReference[]|false */
private array|false $classConstantReferences = false;

private function __construct()
{
}
Expand Down Expand Up @@ -244,6 +254,7 @@ public static function createEmpty(): self
$self->isAllowedPrivateMutation = false;
$self->hasConsistentConstructor = false;
$self->acceptsNamedArguments = true;
$self->classConstantReferences = [];

return $self;
}
Expand Down Expand Up @@ -300,6 +311,7 @@ public function merge(ResolvedPhpDocBlock $parent, InheritedPhpDocParameterMappi
$result->isAllowedPrivateMutation = $this->isAllowedPrivateMutation();
$result->hasConsistentConstructor = $this->hasConsistentConstructor();
$result->acceptsNamedArguments = $acceptsNamedArguments;
$result->classConstantReferences = $this->getClassConstantReferences();

return $result;
}
Expand Down Expand Up @@ -1148,4 +1160,63 @@ private static function resolveTemplateTypeInTag(
return $tag->withType($type);
}

/**
* @return PhpDocClassConstantReference[]
*/
public function getClassConstantReferences(): array
{
if ($this->classConstantReferences !== false) {
return $this->classConstantReferences;
}

$nameScope = $this->nameScope;
if ($nameScope === null) {
$this->classConstantReferences = [];
return $this->classConstantReferences;
}

$result = [];
foreach ($this->phpDocNodes as $phpDocNode) {
$this->collectConstFetchNodes($phpDocNode, $nameScope, $result);
}

$this->classConstantReferences = $result;

return $result;
}

/**
* @param PhpDocClassConstantReference[] $result
*/
private function collectConstFetchNodes(PhpDocAstNode $node, NameScope $nameScope, array &$result): void
{
if ($node instanceof ConstFetchNode) {
if ($node->className !== '') {
if (in_array(strtolower($node->className), ['self', 'static'], true)) {
$className = $nameScope->getClassName();
} else {
$className = $nameScope->resolveStringName($node->className);
}

if ($className !== null) {
$result[] = new PhpDocClassConstantReference($className, $node->name);
}
}
return;
}

foreach (get_object_vars($node) as $prop) {
if ($prop instanceof PhpDocAstNode) {
$this->collectConstFetchNodes($prop, $nameScope, $result);
} elseif (is_array($prop)) {
foreach ($prop as $item) {
if (!($item instanceof PhpDocAstNode)) {
continue;
}
$this->collectConstFetchNodes($item, $nameScope, $result);
}
}
}
}

}
42 changes: 42 additions & 0 deletions src/Rules/DeadCode/UnusedPrivateConstantRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Node\ClassConstantsNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Rules\Constants\AlwaysUsedClassConstantsExtensionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ObjectType;
use function array_keys;
use function preg_match;
use function preg_quote;
use function sprintf;
use function str_contains;
use function str_replace;

/**
* @implements Rule<ClassConstantsNode>
Expand Down Expand Up @@ -93,6 +99,10 @@ public function processNode(Node $node, Scope $scope): array
unset($constants[$fetchNode->name->toString()]);
}

if ($constants !== []) {
$this->removePhpDocReferencedConstants($node, $classReflection, $constants);
}

$errors = [];
foreach ($constants as $constantName => $constantNode) {
$errors[] = RuleErrorBuilder::message(sprintf('Constant %s::%s is unused.', $classReflection->getDisplayName(), $constantName))
Expand All @@ -105,4 +115,36 @@ public function processNode(Node $node, Scope $scope): array
return $errors;
}

/**
* @param array<string, Node\Const_> $constants
*/
private function removePhpDocReferencedConstants(ClassConstantsNode $node, ClassReflection $classReflection, array &$constants): void
{
$className = $classReflection->getName();

foreach ($node->getPhpDocFetches() as $phpDocFetch) {
if ($phpDocFetch->getClassName() !== $className) {
continue;
}

$name = $phpDocFetch->getConstantName();
if (str_contains($name, '*')) {
$pattern = '{^' . str_replace('\\*', '.*', preg_quote($name, '{')) . '$}D';
foreach (array_keys($constants) as $constantName) {
if (preg_match($pattern, $constantName) !== 1) {
continue;
}

unset($constants[$constantName]);
}
} else {
unset($constants[$name]);
}

if ($constants === []) {
return;
}
}
}

}
3 changes: 1 addition & 2 deletions tests/PHPStan/Analyser/AnalyserIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1200,8 +1200,7 @@ public function testBug9039(): void
{
// crash
$errors = $this->runAnalyse(__DIR__ . '/data/bug-9039.php');
$this->assertCount(1, $errors);
$this->assertSame('Constant Bug9039\Test::RULES is unused.', $errors[0]->getMessage());
$this->assertNoErrors($errors);
}

#[RequiresPhp('>= 8.0.0')]
Expand Down
11 changes: 11 additions & 0 deletions tests/PHPStan/Rules/DeadCode/UnusedPrivateConstantRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,15 @@ public function testDynamicConstantFetch(): void
]);
}

public function testBug6415(): void
{
$this->analyse([__DIR__ . '/data/bug-6415.php'], [
[
'Constant Bug6415\MixedUsage::ACTUALLY_UNUSED is unused.',
141,
'See: https://phpstan.org/developing-extensions/always-used-class-constants',
],
]);
}

}
Loading
Loading