Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Rector\Tests\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector\Fixture;

final class NarrowerPropertyType
{
private object $entity;

public function __construct(?object $entity)
{
$this->entity = $entity;
}
}

?>
-----
<?php

namespace Rector\Tests\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector\Fixture;

final class NarrowerPropertyType
{
public function __construct(private object $entity)
{
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\Tests\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector\Fixture;

final class SkipWiderPropertyType
{
public private(set) ?object $entity = null;
Comment thread
TomasVotruba marked this conversation as resolved.
Outdated

public function __construct(object $entity)
{
$this->entity = $entity;
}

public function clear(): void
{
$this->entity = null;
}
Comment thread
TomasVotruba marked this conversation as resolved.
}
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ public function refactor(Node $node): ?Node
continue;
}

if ($this->shouldSkipWiderPropertyType($property, $param)) {
continue;
}

$hasChanged = true;

// remove property from class
Expand Down Expand Up @@ -479,4 +483,32 @@ private function shouldUsePropertyTypeForPromotedParam(Property $property, Param

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);
}
}
Loading