Skip to content

Commit

Permalink
Fix getter method property substitution when the readable types don't…
Browse files Browse the repository at this point in the history
… match.
  • Loading branch information
mad-briller committed Jul 15, 2022
1 parent db7012e commit c5f7145
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
@@ -0,0 +1,37 @@
<?php

namespace Carbon;

/**
* @property-read int $dayOfWeek
*/
final class Carbon {
/**
* @param int $day
*
* @return bool
*/
public function isDayOfWeek($day)
{
return $day === 1;
}

public function __get()
{

}
}

final class DemoFile
{
public $weekday;
public function run()
{
$carbon = new Carbon();
if ($this->weekday === $carbon->dayOfWeek) {
return 1;
}

return 0;
}
}
Expand Up @@ -112,7 +112,7 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node
return null;
}

return $this->refactorPropertyFetch($node);
return $this->refactorPropertyFetch($node, $scope);
}

/**
Expand All @@ -133,7 +133,7 @@ private function shouldSkipPropertyFetch(PropertyFetch $propertyFetch): bool
return $parent->var === $propertyFetch;
}

private function refactorPropertyFetch(PropertyFetch $propertyFetch): MethodCall|null
private function refactorPropertyFetch(PropertyFetch $propertyFetch, Scope $scope): MethodCall|null
{
$callerType = $this->getType($propertyFetch->var);
if (! $callerType instanceof ObjectType) {
Expand All @@ -150,12 +150,23 @@ private function refactorPropertyFetch(PropertyFetch $propertyFetch): MethodCall
return null;
}

$property = $callerType->getProperty($propertyName, $scope);
$propertyType = $property->getReadableType();

$possibleGetterMethodNames = $this->resolvePossibleGetMethodNames($propertyName);

foreach ($possibleGetterMethodNames as $possibleGetterMethodName) {
if (! $callerType->hasMethod($possibleGetterMethodName)->yes()) {
continue;
}
$methodReflection = $callerType->getMethod($possibleGetterMethodName, $scope);

$variant = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants());
$returnType = $variant->getReturnType();

if (! $propertyType->isSuperTypeOf($returnType)->yes()) {
continue;
}

return $this->nodeFactory->createMethodCall($propertyFetch->var, $possibleGetterMethodName);
}
Expand Down

0 comments on commit c5f7145

Please sign in to comment.