Skip to content

Commit

Permalink
Detect unused properties that are written to inside arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Dec 11, 2021
1 parent 19ae9e8 commit b558748
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ public static function analyze(

$naive_property_exists = $codebase->properties->propertyExists(
$property_id,
true,
!$in_assignment,
$statements_analyzer,
$context,
$codebase->collect_locations ? new CodeLocation($statements_analyzer->getSource(), $stmt) : null
Expand All @@ -252,7 +252,7 @@ public static function analyze(
if ($new_class_storage
&& ($codebase->properties->propertyExists(
$new_property_id,
true,
!$in_assignment,
$statements_analyzer,
$context,
$codebase->collect_locations
Expand Down
35 changes: 35 additions & 0 deletions tests/UnusedCodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,17 @@ public function validate(): void
foobar
',
],
'usedPropertyAsAssignmentKey' => [
'<?php
class A {
public string $foo = "bar";
public array $bar = [];
}
$a = new A();
$a->bar[$a->foo] = "bar";
print_r($a->bar);',
],
];
}

Expand Down Expand Up @@ -1248,6 +1259,30 @@ class A {
'error_message' => 'PossiblyUnusedProperty',
'error_levels' => ['UnusedVariable'],
],
'possiblyUnusedPropertyWrittenNeverRead' => [
'<?php
class A {
/** @var string */
public $foo = "hello";
}
$a = new A();
$a->foo = "bar";',
'error_message' => 'PossiblyUnusedProperty',
'error_levels' => ['UnusedVariable'],
],
'possiblyUnusedPropertyWithArrayWrittenNeverRead' => [
'<?php
class A {
/** @var list<string> */
public array $foo = [];
}
$a = new A();
$a->foo[] = "bar";',
'error_message' => 'PossiblyUnusedProperty',
'error_levels' => ['UnusedVariable'],
],
'unusedProperty' => [
'<?php
class A {
Expand Down

0 comments on commit b558748

Please sign in to comment.