Repository navigation
Expand file tree
/
Copy pathUnusedPrivatePropertyRule.php
More file actions
379 lines (336 loc) · 11.3 KB
/
Copy pathUnusedPrivatePropertyRule.php
File metadata and controls
379 lines (336 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php declare(strict_types = 1);
namespace PHPStan\Rules\DeadCode;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredExtensions;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\ExtensionsCollection;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Node\ClassPropertiesNode;
use PHPStan\Node\ClassPropertyNode;
use PHPStan\Node\Property\PropertyRead;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
use PHPStan\Rules\Properties\ReadWritePropertiesExtension;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ObjectType;
use function array_key_exists;
use function array_keys;
use function array_map;
use function count;
use function is_string;
use function lcfirst;
use function sprintf;
use function str_contains;
/**
* @implements Rule<ClassPropertiesNode>
*/
#[RegisteredRule(level: 4)]
final class UnusedPrivatePropertyRule implements Rule
{
/**
* @param ExtensionsCollection<ReadWritePropertiesExtension> $extensions
* @param string[] $alwaysWrittenTags
* @param string[] $alwaysReadTags
*/
public function __construct(
#[AutowiredExtensions(of: ReadWritePropertiesExtension::class)]
private ExtensionsCollection $extensions,
#[AutowiredParameter(ref: '%propertyAlwaysWrittenTags%')]
private array $alwaysWrittenTags,
#[AutowiredParameter(ref: '%propertyAlwaysReadTags%')]
private array $alwaysReadTags,
#[AutowiredParameter]
private bool $checkUninitializedProperties,
)
{
}
public function getNodeType(): string
{
return ClassPropertiesNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!$node->getClass() instanceof Node\Stmt\Class_) {
return [];
}
$classReflection = $node->getClassReflection();
$classType = new ObjectType($classReflection->getName(), classReflection: $classReflection);
// A property node declared in a trait only reaches us when NodeScopeResolver traversed
// that trait's body, which it does for analysed files only. Its presence therefore
// proves the trait's own usages are visible.
$propertyNamesDeclaredInTraitBody = [];
foreach ($node->getProperties() as $property) {
if (!$property->isDeclaredInTrait()) {
continue;
}
$propertyNamesDeclaredInTraitBody[$property->getName()] = true;
}
$properties = [];
foreach ($node->getProperties() as $property) {
if (!$property->isPrivate()) {
continue;
}
if ($property->isDeclaredInTrait()) {
continue;
}
if (
!array_key_exists($property->getName(), $propertyNamesDeclaredInTraitBody)
&& $this->isRedeclaringPrivateTraitProperty($classReflection, $property->getName())
) {
continue;
}
$alwaysRead = !$property->isReadable();
$alwaysWritten = !$property->isWritable();
if ($property->getPhpDoc() !== null) {
$text = $property->getPhpDoc();
foreach ($this->alwaysReadTags as $tag) {
if (!str_contains($text, $tag)) {
continue;
}
$alwaysRead = true;
break;
}
foreach ($this->alwaysWrittenTags as $tag) {
if (!str_contains($text, $tag)) {
continue;
}
$alwaysWritten = true;
break;
}
}
$propertyName = $property->getName();
if (!$alwaysRead || !$alwaysWritten) {
if (!$classReflection->hasNativeProperty($propertyName)) {
continue;
}
$propertyReflection = $classReflection->getNativeProperty($propertyName);
foreach ($this->extensions->getAll() as $extension) {
if ($alwaysRead && $alwaysWritten) {
break;
}
if (!$alwaysRead && $extension->isAlwaysRead($propertyReflection, $propertyName)) {
$alwaysRead = true;
}
if ($alwaysWritten || !$extension->isAlwaysWritten($propertyReflection, $propertyName)) {
continue;
}
$alwaysWritten = true;
}
}
$read = $alwaysRead;
$written = $alwaysWritten || $property->getDefault() !== null;
$properties[$propertyName] = [
'read' => $read,
'written' => $written,
'node' => $property,
'onlyReadable' => $property->isReadable() && !$property->isWritable(),
'onlyWritable' => $property->isWritable() && !$property->isReadable(),
'hasTrueRead' => $alwaysRead,
];
}
foreach ($node->getPropertyUsages() as $usage) {
$usageScope = $usage->getScope();
$fetch = $usage->getFetch();
if ($fetch->name instanceof Node\Identifier) {
$propertyName = $fetch->name->toString();
$propertyNames = [$propertyName];
if (
$usageScope->getFunction() !== null
&& $fetch instanceof Node\Expr\PropertyFetch
&& $fetch->var instanceof Node\Expr\Variable
&& is_string($fetch->var->name)
&& $fetch->var->name === 'this'
) {
$methodReflection = $usageScope->getFunction();
if (
$methodReflection instanceof PhpMethodFromParserNodeReflection
&& $methodReflection->isPropertyHook()
&& $methodReflection->getHookedPropertyName() === $propertyName
&& (
$methodReflection->getPropertyHookName() === 'set'
|| $usage instanceof PropertyRead
)
) {
continue;
}
}
} else {
$propertyNameType = $usageScope->getType($fetch->name);
$strings = $propertyNameType->getConstantStrings();
if (count($strings) === 0) {
// handle subtractions of a dynamic property fetch
foreach (array_keys($properties) as $propertyName) {
if ((new ConstantStringType($propertyName))->isSuperTypeOf($propertyNameType)->no()) {
continue;
}
unset($properties[$propertyName]);
}
continue;
}
$propertyNames = array_map(static fn (ConstantStringType $type): string => $type->getValue(), $strings);
}
if ($fetch instanceof Node\Expr\PropertyFetch) {
$fetchedOnType = $usageScope->getType($fetch->var);
} else {
if ($fetch->class instanceof Node\Name) {
$fetchedOnType = $usageScope->resolveTypeByName($fetch->class);
} else {
$fetchedOnType = $usageScope->getType($fetch->class)->getObjectTypeOrClassStringObjectType();
}
}
foreach ($propertyNames as $propertyName) {
if (!array_key_exists($propertyName, $properties)) {
continue;
}
$propertyNode = $properties[$propertyName]['node'];
if ($propertyNode->isStatic()) {
$propertyReflection = $usageScope->getStaticPropertyReflection($fetchedOnType, $propertyName);
} else {
$propertyReflection = $usageScope->getInstancePropertyReflection($fetchedOnType, $propertyName);
}
if ($propertyReflection === null) {
if (!$classType->isSuperTypeOf($fetchedOnType)->no()) {
if ($usage instanceof PropertyRead) {
$properties[$propertyName]['read'] = true;
$properties[$propertyName]['hasTrueRead'] = true;
} else {
$properties[$propertyName]['written'] = true;
}
}
continue;
}
if ($propertyReflection->getDeclaringClass()->getName() !== $classReflection->getName()) {
if (!$classType->isSuperTypeOf($fetchedOnType)->no()) {
if ($usage instanceof PropertyRead) {
$properties[$propertyName]['read'] = true;
$properties[$propertyName]['hasTrueRead'] = true;
} else {
$properties[$propertyName]['written'] = true;
}
}
continue;
}
if ($usage instanceof PropertyRead) {
$properties[$propertyName]['read'] = true;
if (!$this->isPropertySelfWrite($usageScope, $propertyName, $propertyNode, $classReflection->getName())) {
$properties[$propertyName]['hasTrueRead'] = true;
}
} else {
$properties[$propertyName]['written'] = true;
if ($usage->isByReference()) {
$properties[$propertyName]['read'] = true;
$properties[$propertyName]['hasTrueRead'] = true;
}
}
}
}
foreach ($properties as $propertyName => $data) {
if (!$data['read'] || $data['hasTrueRead']) {
continue;
}
if (!$data['node']->isPromoted()) {
continue;
}
$properties[$propertyName]['read'] = false;
}
[$uninitializedProperties] = $node->getUninitializedProperties($scope, []);
$errors = [];
foreach ($properties as $name => $data) {
$propertyNode = $data['node'];
if ($propertyNode->isStatic()) {
$propertyName = sprintf('Static property %s::$%s', $classReflection->getDisplayName(), $name);
} else {
$propertyName = sprintf('Property %s::$%s', $classReflection->getDisplayName(), $name);
}
$tip = sprintf('See: %s', 'https://phpstan.org/developing-extensions/always-read-written-properties');
if (!$data['read']) {
if (!$data['written']) {
$errors[] = RuleErrorBuilder::message(sprintf('%s is unused.', $propertyName))
->line($propertyNode->getStartLine())
->tip($tip)
->identifier('property.unused')
->build();
} else {
if ($data['onlyReadable']) {
$errors[] = RuleErrorBuilder::message(sprintf('Readable %s is never read.', lcfirst($propertyName)))
->line($propertyNode->getStartLine())
->identifier('property.neverRead')
->build();
} else {
$errors[] = RuleErrorBuilder::message(sprintf('%s is never read, only written.', $propertyName))
->line($propertyNode->getStartLine())
->identifier('property.onlyWritten')
->tip($tip)
->build();
}
}
} elseif (!$data['written'] && (!array_key_exists($name, $uninitializedProperties) || !$this->checkUninitializedProperties)) {
if ($data['onlyWritable']) {
$errors[] = RuleErrorBuilder::message(sprintf('Writable %s is never written.', lcfirst($propertyName)))
->line($propertyNode->getStartLine())
->identifier('property.neverWritten')
->build();
} else {
$errors[] = RuleErrorBuilder::message(sprintf('%s is never written, only read.', $propertyName))
->line($propertyNode->getStartLine())
->identifier('property.onlyRead')
->tip($tip)
->build();
}
}
}
return $errors;
}
/**
* A private property redeclared from a used trait is the very property the trait's
* own methods read and write. Callers must only rely on this when the trait's body was
* not traversed, otherwise those usages are visible and no guessing is needed.
*/
private function isRedeclaringPrivateTraitProperty(ClassReflection $classReflection, string $propertyName): bool
{
foreach ($classReflection->getTraits() as $trait) {
if (!$trait->hasNativeProperty($propertyName)) {
continue;
}
if (!$trait->getNativeProperty($propertyName)->isPrivate()) {
continue;
}
return true;
}
return false;
}
private function isPropertySelfWrite(
Scope $usageScope,
string $propertyName,
ClassPropertyNode $propertyNode,
string $className,
): bool
{
if (!$propertyNode->isPromoted()) {
return false;
}
$callStack = $usageScope->getFunctionCallStackWithParameters();
if ($callStack === []) {
return false;
}
$lastCall = $callStack[count($callStack) - 1];
[$calleeReflection, $parameterReflection] = $lastCall;
if (!$calleeReflection instanceof MethodReflection) {
return false;
}
if ($calleeReflection->getName() !== '__construct') {
return false;
}
if ($calleeReflection->getDeclaringClass()->getName() !== $className) {
return false;
}
if ($parameterReflection === null) {
return false;
}
return $parameterReflection->getName() === $propertyName;
}
}