Skip to content

Commit

Permalink
Detect accessing static property on a trait
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Mar 16, 2020
1 parent e089754 commit 88d2607
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Rules/Properties/AccessStaticPropertiesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,18 @@ public function processNode(Node $node, Scope $scope): array
} else {
$messages = $this->classCaseSensitivityCheck->checkClassNames([new ClassNameNodePair($class, $node->class)]);
}

$classReflection = $this->reflectionProvider->getClass($class);
$className = $this->reflectionProvider->getClass($class)->getName();
if ($classReflection->isTrait()) {
return [
RuleErrorBuilder::message(sprintf(
'Access to static property $%s on trait %s.',
$name,
$className
))->build(),
];
}
}

$classType = new ObjectType($className);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,14 @@ public function testAccessStaticProperties(): void
'Access to an undefined static property AccessInIsset::$foo.',
185,
],
[
'Access to static property $foo on trait TraitWithStaticProperty.',
204,
],
[
'Access to static property $foo on an unknown class TraitWithStaticProperty.',
209,
],
]);
}

Expand Down
22 changes: 22 additions & 0 deletions tests/PHPStan/Rules/Properties/data/access-static-properties.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,25 @@ public function doBar()
}

}

trait TraitWithStaticProperty
{

public static $foo;

}

class MethodAccessingTraitProperty
{

public function doFoo(): void
{
echo TraitWithStaticProperty::$foo;
}

public function doBar(TraitWithStaticProperty $a): void
{
echo $a::$foo;
}

}

2 comments on commit 88d2607

@filip-t
Copy link

@filip-t filip-t commented on 88d2607 Jun 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From PHP docs:

Traits can define static variables, static methods and static properties.

Looks like the change for static methods has already been reverted. Shouldn't this be reverted as well? @ondrejmirtes
phpstan/phpstan#4107

@ondrejmirtes
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@filip-t If you have a false positive, please open an issue with phpstan.org reproduction link.

Please sign in to comment.