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
19 changes: 18 additions & 1 deletion src/Node/ClassStatementsGatherer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use PHPStan\Node\Printer\ExprPrinter;
use PHPStan\Node\Property\PropertyAssign;
use PHPStan\Node\Property\PropertyRead;
use PHPStan\Node\Property\PropertyReferenceBinding;
use PHPStan\Node\Property\PropertyWrite;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
Expand Down Expand Up @@ -159,8 +160,14 @@ private function gatherNodes(Node $node, Scope $scope): void
if ($node instanceof ClassPropertyNode) {
$this->properties[] = $node;
if ($node->isPromoted()) {
$propertyFetch = new PropertyFetch(new Expr\Variable('this'), new Identifier($node->getName()));
$originalNode = $node->getOriginalNode();
if ($originalNode instanceof Node\Param && $originalNode->byRef) {
// the property shares its value with the referenced argument, which can read it elsewhere
$this->propertyUsages[] = new PropertyRead($propertyFetch, $scope);
}
$this->propertyUsages[] = new PropertyWrite(
new PropertyFetch(new Expr\Variable('this'), new Identifier($node->getName())),
$propertyFetch,
$scope,
true,
$node,
Expand Down Expand Up @@ -228,6 +235,16 @@ private function gatherNodes(Node $node, Scope $scope): void
return;
}
if ($node instanceof Expr\AssignRef) {
$boundVar = $node->var;
while ($boundVar instanceof ArrayDimFetch) {
$boundVar = $boundVar->var;
}
if (
($boundVar instanceof PropertyFetch || $boundVar instanceof StaticPropertyFetch)
&& PropertyReferenceBinding::isReadThroughReference($node->expr, $scope, $this->methods)
) {
$this->propertyUsages[] = new PropertyRead($boundVar, $scope);
}
if (!$node->expr instanceof PropertyFetch && !$node->expr instanceof StaticPropertyFetch) {
$this->gatherNodes($node->expr, $scope);
return;
Expand Down
94 changes: 94 additions & 0 deletions src/Node/Property/PropertyReferenceBinding.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php declare(strict_types = 1);

namespace PHPStan\Node\Property;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\NodeFinder;
use PHPStan\Analyser\Scope;
use PHPStan\Node\ClassMethod;
use PHPStan\Reflection\MethodReflection;
use function in_array;
use function is_string;
use function spl_object_id;
use function strtolower;

/**
* Decides whether binding a property by reference (`$this->prop = &$expr`)
* lets its value be read through the other side of the reference.
*
* Called from the native ClassStatementsGatherer in turbo-ext as well.
*/
final class PropertyReferenceBinding

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Dunno if there is a better name/place for this service...

{

private const VARIABLE_READING_FUNCTIONS = ['compact', 'get_defined_vars'];

/**
* @param array<ClassMethod> $methods methods gathered so far in the class
*/
public static function isReadThroughReference(Expr $referencedExpr, Scope $scope, array $methods): bool

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I don't really like this AST based node-finder deep seek, but since it only happens for by-ref parameters/promoted-properties, I think it is fine

{
if (!$referencedExpr instanceof Variable || !is_string($referencedExpr->name)) {
return true;
}
if ($scope->isInAnonymousFunction()) {
return true;
}

$function = $scope->getFunction();
if (!$function instanceof MethodReflection) {
return true;
}

$methodName = strtolower($function->getName());
$methodNode = null;
foreach ($methods as $method) {
if ($method->getNode()->name->toLowerString() !== $methodName) {
continue;
}
$methodNode = $method->getNode();
}
if ($methodNode === null || $methodNode->stmts === null) {
return true;
}

$variableName = $referencedExpr->name;
foreach ($methodNode->params as $param) {
if (!$param->var instanceof Variable || $param->var->name !== $variableName) {
continue;
}

// the caller holds the other side of a by-ref parameter
return $param->byRef;
}

// a local variable keeps the value alive only while something else in the method uses it
// (global/static declarations, closure uses, further reads, passing it on, ...)
$overwrittenVariables = [];
$nodeFinder = new NodeFinder();
foreach ($nodeFinder->findInstanceOf($methodNode->stmts, Assign::class) as $assign) {
$overwrittenVariables[spl_object_id($assign->var)] = true;
}

return $nodeFinder->findFirst($methodNode->stmts, static function (Node $node) use ($referencedExpr, $variableName, $overwrittenVariables): bool {
if ($node instanceof Variable) {
if (!is_string($node->name)) {
return true;
}

return $node->name === $variableName
&& $node !== $referencedExpr
&& !isset($overwrittenVariables[spl_object_id($node)]);
}

return $node instanceof FuncCall
&& $node->name instanceof Node\Name
&& in_array($node->name->toLowerString(), self::VARIABLE_READING_FUNCTIONS, true);
}) !== null;
}

}
63 changes: 63 additions & 0 deletions tests/PHPStan/Rules/DeadCode/UnusedPrivatePropertyRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,4 +516,67 @@ public function testBug12201(): void
]);
}

public function testBug15886(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886.php'], []);
}

#[RequiresPhp('>= 8.0.0')]
public function testBug15886Promoted(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-promoted.php'], []);
}

public function testBug15886Static(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-static.php'], []);
}

public function testBug15886Local(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-local.php'], [
[
'Property Bug15886Local\\ThrowawayLocal::$cache is never read, only written.',
9,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
[
'Property Bug15886Local\\ByValueParameter::$cache is never read, only written.',
28,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
[
'Static property Bug15886Local\\StaticPropertyThrowawayLocal::$cache is never read, only written.',
173,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

public function testBug15886ArrayOffset(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-array-offset.php'], [
[
'Property Bug15886ArrayOffset\\ArrayOffsetThrowawayLocal::$counters is never read, only written.',
56,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

}
68 changes: 68 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/bug-15886-array-offset.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php declare(strict_types = 1);

namespace Bug15886ArrayOffset;

class ArrayOffset
{
/** @var array<string, int> */
private array $counters = [];

public function bind(int &$counter): void
{
$this->counters['requests'] = &$counter;
}

public function reset(): void
{
$this->counters['requests'] = 0;
}
}

class NestedArrayOffset
{
/** @var array<string, array<string, int>> */
private array $counters = [];

public function bind(int &$counter): void
{
$this->counters['http']['requests'] = &$counter;
}

public function reset(): void
{
$this->counters['http']['requests'] = 0;
}
}

class StaticArrayOffset
{
/** @var array<string, int> */
private static array $counters = [];

public static function bind(int &$counter): void
{
self::$counters['requests'] = &$counter;
}

public static function reset(): void
{
self::$counters['requests'] = 0;
}
}

class ArrayOffsetThrowawayLocal
{
/** @var array<string, int> */
private array $counters = [];

public function bind(): void
{
$counter = 0;
$this->counters['requests'] = &$counter;
}

public function reset(): void
{
$this->counters['requests'] = 0;
}
}
Loading
Loading