forked from rectorphp/rector-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassPropertyAssignToConstructorPromotionRector.php
More file actions
514 lines (426 loc) · 17.1 KB
/
Copy pathClassPropertyAssignToConstructorPromotionRector.php
File metadata and controls
514 lines (426 loc) · 17.1 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<?php
declare(strict_types=1);
namespace Rector\Php80\Rector\Class_;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Identifier;
use PhpParser\Node\IntersectionType;
use PhpParser\Node\Name;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\UnionType;
use PhpParser\NodeVisitor;
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\MixedType;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\Naming\PropertyRenamer\PropertyPromotionRenamer;
use Rector\Naming\VariableRenamer;
use Rector\NodeAnalyzer\ParamAnalyzer;
use Rector\NodeTypeResolver\TypeComparator\TypeComparator;
use Rector\Php80\DocBlock\PropertyPromotionDocBlockMerger;
use Rector\Php80\Guard\MakePropertyPromotionGuard;
use Rector\Php80\NodeAnalyzer\PromotedPropertyCandidateResolver;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\Rector\AbstractRector;
use Rector\Reflection\ReflectionResolver;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\ValueObject\MethodName;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector\ClassPropertyAssignToConstructorPromotionRectorTest
*/
final class ClassPropertyAssignToConstructorPromotionRector extends AbstractRector implements MinPhpVersionInterface, ConfigurableRectorInterface
{
/**
* @api
*/
public const string INLINE_PUBLIC = 'inline_public';
/**
* @api
*/
public const string RENAME_PROPERTY = 'rename_property';
/**
* @api
*/
public const string ALLOW_MODEL_BASED_CLASSES = 'allow_model_based_classes';
/**
* Default to false, which only apply changes:
*
* – private modifier property
* - protected/public modifier property when property typed
*
* Set to true will allow change whether property is typed or not as far as not forbidden, eg: callable type, null type, etc.
*/
private bool $inlinePublic = false;
/**
* Set to false will skip property promotion when parameter and property have different names.
*/
private bool $renameProperty = true;
/**
* Set to false will skip property promotion on model based classes
*/
private bool $allowModelBasedClasses = true;
public function __construct(
private readonly PromotedPropertyCandidateResolver $promotedPropertyCandidateResolver,
private readonly VariableRenamer $variableRenamer,
private readonly ParamAnalyzer $paramAnalyzer,
private readonly PropertyPromotionDocBlockMerger $propertyPromotionDocBlockMerger,
private readonly MakePropertyPromotionGuard $makePropertyPromotionGuard,
private readonly TypeComparator $typeComparator,
private readonly ReflectionResolver $reflectionResolver,
private readonly PropertyPromotionRenamer $propertyPromotionRenamer,
private readonly PhpDocInfoFactory $phpDocInfoFactory,
private readonly StaticTypeMapper $staticTypeMapper,
private readonly ValueResolver $valueResolver,
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Change simple property init and assign to constructor promotion',
[
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public float $price;
public function __construct(
float $price = 0.0
) {
$this->price = $price;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function __construct(
public float $price = 0.0
) {
}
}
CODE_SAMPLE
,
[
self::INLINE_PUBLIC => false,
self::RENAME_PROPERTY => true,
self::ALLOW_MODEL_BASED_CLASSES => true,
]
),
]
);
}
/**
* @param array<string, mixed> $configuration
*/
public function configure(array $configuration): void
{
$this->inlinePublic = $configuration[self::INLINE_PUBLIC] ?? false;
$this->renameProperty = $configuration[self::RENAME_PROPERTY] ?? true;
$this->allowModelBasedClasses = $configuration[self::ALLOW_MODEL_BASED_CLASSES] ?? true;
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Class_::class];
}
/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
$constructClassMethod = $node->getMethod(MethodName::CONSTRUCT);
if (! $constructClassMethod instanceof ClassMethod) {
return null;
}
$promotionCandidates = $this->promotedPropertyCandidateResolver->resolveFromClass(
$node,
$constructClassMethod,
$this->allowModelBasedClasses
);
if ($promotionCandidates === []) {
return null;
}
$classReflection = $this->reflectionResolver->resolveClassReflection($node);
if (! $classReflection instanceof ClassReflection) {
return null;
}
$constructorPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($constructClassMethod);
$hasChanged = false;
foreach ($promotionCandidates as $promotionCandidate) {
$param = $promotionCandidate->getParam();
if ($this->shouldSkipParam($param)) {
continue;
}
$property = $promotionCandidate->getProperty();
if (! $this->makePropertyPromotionGuard->isLegal(
$node,
$classReflection,
$property,
$param,
$this->inlinePublic
)) {
continue;
}
$paramName = $this->getName($param);
// rename also following calls
$propertyName = $this->getName($property->props[0]);
if (! $this->renameProperty && $paramName !== $propertyName) {
continue;
}
if ($this->shouldSkipPropertyOrParam($property, $param)) {
continue;
}
if ($this->shouldSkipNarrowingVarDoc($property, $param, $constructorPhpDocInfo, $paramName)) {
continue;
}
if ($this->shouldSkipWiderPropertyType($property, $param)) {
continue;
}
$hasChanged = true;
// remove property from class
unset($node->stmts[$promotionCandidate->getPropertyStmtPosition()]);
// remove assign in constructor
unset($constructClassMethod->stmts[$promotionCandidate->getConstructorAssignStmtPosition()]);
$oldParamName = $this->getName($param);
$this->variableRenamer->renameVariableInFunctionLike($constructClassMethod, $oldParamName, $propertyName);
$paramTagValueNode = $constructorPhpDocInfo->getParamTagValueByName($paramName);
if (! $paramTagValueNode instanceof ParamTagValueNode) {
$this->propertyPromotionDocBlockMerger->decorateParamWithPropertyPhpDocInfo(
$constructClassMethod,
$property,
$param,
$paramName
);
} elseif ($paramTagValueNode->parameterName !== '$' . $propertyName) {
$this->propertyPromotionRenamer->renameParamDoc(
$constructorPhpDocInfo,
$constructClassMethod,
$param,
$paramTagValueNode->parameterName,
$propertyName
);
}
// property name has higher priority
$paramName = $this->getName($property);
$param->var = new Variable($paramName);
$param->flags = $property->flags;
$param->hooks = $property->hooks;
// copy attributes of the old property
$param->attrGroups = array_merge($param->attrGroups, $property->attrGroups);
$this->processUnionType($property, $param);
$this->propertyPromotionDocBlockMerger->mergePropertyAndParamDocBlocks(
$property,
$param,
$paramTagValueNode
);
// update variable to property fetch references
$this->traverseNodesWithCallable((array) $constructClassMethod->stmts, function (Node $node) use (
$promotionCandidate,
$propertyName
): null|int|PropertyFetch {
if ($node instanceof Class_ || $node instanceof FunctionLike) {
return NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN;
}
if (! $node instanceof Variable) {
return null;
}
if (! $this->isName($node, $promotionCandidate->getParamName())) {
return null;
}
return new PropertyFetch(new Variable('this'), $propertyName);
});
}
if (! $hasChanged) {
return null;
}
return $node;
}
public function provideMinPhpVersion(): int
{
return PhpVersionFeature::PROPERTY_PROMOTION;
}
private function processUnionType(Property $property, Param $param): void
{
if ($this->shouldUsePropertyTypeForPromotedParam($property, $param)) {
$param->type = $property->type;
return;
}
if (! $param->type instanceof Node) {
return;
}
$paramType = $this->getType($param->type);
if ($this->shouldRemoveNullFromForPromotedParamType($property, $param)) {
$paramType = TypeCombinator::removeNull($paramType);
$param->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($paramType, TypeKind::PARAM);
}
if (! $param->default instanceof Expr) {
return;
}
$defaultType = $this->getType($param->default);
if ($this->typeComparator->isSubtype($defaultType, $paramType)) {
return;
}
if ($this->typeComparator->areTypesEqual($defaultType, $paramType)) {
return;
}
if ($paramType instanceof MixedType) {
return;
}
$paramType = TypeCombinator::union($paramType, $defaultType);
$param->type = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($paramType, TypeKind::PARAM);
}
private function shouldSkipParam(Param $param): bool
{
if ($param->variadic) {
return true;
}
if ($this->paramAnalyzer->isNullable($param)) {
/** @var NullableType $type */
$type = $param->type;
$type = $type->type;
} else {
$type = $param->type;
}
if ($this->isCallableTypeIdentifier($type)) {
return true;
}
if (! $type instanceof UnionType) {
return false;
}
return array_any(
$type->types,
fn (Identifier|IntersectionType|Name $type): bool => $this->isCallableTypeIdentifier($type)
);
}
private function isCallableTypeIdentifier(?Node $node): bool
{
if (! $node instanceof Identifier) {
return false;
}
return $this->isName($node, 'callable');
}
private function shouldSkipPropertyOrParam(Property $property, Param $param): bool
{
foreach ($property->hooks as $hook) {
if (! is_array($hook->body)) {
continue;
}
if (count($hook->body) > 1) {
return true;
}
}
return $property->type instanceof Node
&& $param->type instanceof Node
&& $property->hooks !== []
&& ! $this->nodeComparator->areNodesEqual($property->type, $param->type);
}
/**
* A class-typed property may carry a narrowing @var (e.g. native AdapterInterface, @var CacheProvider) used to
* type calls on the property. Promotion would drop that @var (it is not preserved as a @param here), $property so skip to
* avoid losing type information.
*/
private function shouldSkipNarrowingVarDoc(
Property $property,
Param $param,
PhpDocInfo $constructorPhpDocInfo,
string $paramName
): bool {
if (! $property->type instanceof Node || ! $param->type instanceof Node) {
return false;
}
// an explicit @param already carries the type onto the promoted property
if ($constructorPhpDocInfo->getParamTagValueByName($paramName) instanceof ParamTagValueNode) {
return false;
}
$propertyPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property);
$varTagValueNode = $propertyPhpDocInfo->getVarTagValueNode();
if (! $varTagValueNode instanceof VarTagValueNode) {
return false;
}
// a description keeps the docblock around anyway
if ($varTagValueNode->description !== '') {
return false;
}
$varType = $this->staticTypeMapper->mapPHPStanPhpDocTypeToPHPStanType($varTagValueNode, $property);
// only class-typed @var narrowing is lost; generics, arrays and int ranges are preserved on promotion
if (! $varType instanceof TypeWithClassName) {
return false;
}
$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
return ! $this->typeComparator->areTypesEqual($varType, $paramType);
}
private function shouldRemoveNullFromForPromotedParamType(Property $property, Param $param): bool
{
if (! $property->type instanceof Node || ! $param->type instanceof Node) {
return false;
}
if ($param->default instanceof Expr && $this->valueResolver->isNull($param->default)) {
return false;
}
$propertyType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($property->type);
$type = TypeCombinator::removeNull($propertyType);
if (! $this->typeComparator->areTypesEqual($type, $propertyType)) {
return false;
}
$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
$paramTypeWithoutNull = TypeCombinator::removeNull($paramType);
return ! $this->typeComparator->areTypesEqual($paramTypeWithoutNull, $paramType);
}
private function shouldUsePropertyTypeForPromotedParam(Property $property, Param $param): bool
{
if (! $property->type instanceof Node) {
return false;
}
if (! $param->type instanceof Node) {
return true;
}
$propertyType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($property->type);
$type = TypeCombinator::removeNull($propertyType);
$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
$paramTypeWithoutNull = TypeCombinator::removeNull($paramType);
return $this->typeComparator->areTypesEqual($type, $paramTypeWithoutNull);
}
/**
* Promotion shares one type. When processUnionType would copy the property type onto the
* param and that type is strictly wider (e.g. ?object vs object), skip — otherwise the
* constructor contract is loosened. Narrowing (object vs ?object) stays allowed.
* Interface vs implementation does not fire here: shouldUsePropertyTypeForPromotedParam
* is false when the non-null base types differ.
*/
private function shouldSkipWiderPropertyType(Property $property, Param $param): bool
{
if (! $this->shouldUsePropertyTypeForPromotedParam($property, $param)) {
return false;
}
if (! $property->type instanceof Node || ! $param->type instanceof Node) {
return false;
}
$propertyType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($property->type);
$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
if ($param->default instanceof Expr) {
$paramType = TypeCombinator::union($paramType, $this->getType($param->default));
}
return $this->typeComparator->isSubtype($paramType, $propertyType)
&& ! $this->typeComparator->areTypesEqual($propertyType, $paramType);
}
}