[TypeDeclaration] Add ParamTypeByMethodCallTypeRector (#544)

This commit is contained in:
Tomas Votruba 2021-07-30 12:29:31 +02:00 committed by GitHub
parent 29c28fda87
commit 325c6be3ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 533 additions and 32 deletions

View File

@ -106,7 +106,8 @@
"stubs/Doctrine/Common/Persistence/ObjectManager.php",
"rules-tests/Transform/Rector/FuncCall/FuncCallToMethodCallRector/Source/some_view_function.php",
"rules-tests/TypeDeclaration/Rector/FunctionLike/ReturnTypeDeclarationRector/Source/MyBar.php",
"rules-tests/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector/Source/EventDispatcher.php"
"rules-tests/TypeDeclaration/Rector/Property/CompleteVarDocTypePropertyRector/Source/EventDispatcher.php",
"rules-tests/TypeDeclaration/Rector/ClassMethod/ParamTypeByMethodCallTypeRector/Source/FunctionTyped.php"
]
},
"scripts": {

View File

@ -5,6 +5,8 @@ declare(strict_types=1);
use Rector\TypeDeclaration\Rector\ClassMethod\AddArrayParamDocTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddArrayReturnDocTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeFromCallersRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByParentCallTypeRector;
use Rector\TypeDeclaration\Rector\Closure\AddClosureReturnTypeRector;
use Rector\TypeDeclaration\Rector\FunctionLike\ParamTypeDeclarationRector;
use Rector\TypeDeclaration\Rector\FunctionLike\ReturnTypeDeclarationRector;
@ -20,5 +22,6 @@ return static function (ContainerConfigurator $containerConfigurator): void {
$services->set(AddArrayParamDocTypeRector::class);
$services->set(AddArrayReturnDocTypeRector::class);
// $services->set(AddParamTypeFromCallersRector::class);
$services->set(\Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByParentCallTypeRector::class);
$services->set(ParamTypeByParentCallTypeRector::class);
$services->set(ParamTypeByMethodCallTypeRector::class);
};

View File

@ -2,7 +2,7 @@
namespace Rector\Tests\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector\Fixture;
class FunctionCall
final class SomeFunctionCall
{
private $prop;
@ -22,7 +22,7 @@ class FunctionCall
namespace Rector\Tests\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector\Fixture;
class FunctionCall
final class SomeFunctionCall
{
public function doThing()
{

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use function Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source\function_typed;
final class FuncCallElsewhere
{
public function go($anotherValue, $someValue)
{
function_typed($someValue, $anotherValue);
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use function Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source\function_typed;
final class FuncCallElsewhere
{
public function go(int|bool $anotherValue, $someValue)
{
function_typed($someValue, $anotherValue);
}
}
?>

View File

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
final class SkipConditional
{
public function run($value)
{
if (is_array($value)) {
$this->processArray($value);
}
}
private function processArray(array $value)
{
}
}

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use Nette\Utils\Strings;
final class SkipConditionalWithLatestMethodCall
{
public function run($value)
{
if (\is_array($value)) {
return $this->removeQuotesFromArray($value);
}
if (! is_string($value)) {
return $value;
}
$matches = Strings::match($value, 'some_');
if ($matches === null) {
return $value;
}
return $matches['content'];
}
private function removeQuotesFromArray(array $value)
{
return $value;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source\SomeTypedService;
final class UseDependency
{
public function __construct(
private SomeTypedService $someTypedService
) {
}
public function go($value)
{
$this->someTypedService->run($value);
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source\SomeTypedService;
final class UseDependency
{
public function __construct(
private SomeTypedService $someTypedService
) {
}
public function go(string $value)
{
$this->someTypedService->run($value);
}
}
?>

View File

@ -0,0 +1,31 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source\SomeTypedService;
final class StaticCallElsewhere
{
public function go($value, $first)
{
SomeTypedService::fun($first, $value);
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Fixture;
use Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source\SomeTypedService;
final class StaticCallElsewhere
{
public function go(string $value, $first)
{
SomeTypedService::fun($first, $value);
}
}
?>

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;
final class ParamTypeByMethodCallTypeRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}
/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}
public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}

View File

@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source;
function function_typed($whatever, int|bool $age)
{
}

View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\Source;
final class SomeTypedService
{
public function run(string $name)
{
}
public static function fun($surname, string $name)
{
}
}

View File

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
use Rector\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(ParamTypeByMethodCallTypeRector::class);
};

View File

@ -4,23 +4,59 @@ declare(strict_types=1);
namespace Rector\TypeDeclaration\NodeAnalyzer;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\UnionType;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use Rector\Core\PhpParser\AstResolver;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
final class ParentParamMatcher
final class CallerParamMatcher
{
public function __construct(
private NodeNameResolver $nodeNameResolver,
private AstResolver $astResolver
private AstResolver $astResolver,
private BetterNodeFinder $betterNodeFinder
) {
}
public function matchCallParamType(
StaticCall | MethodCall | FuncCall $call,
Param $param,
Scope $scope
): null | Identifier | Name | NullableType | UnionType {
$callParam = $this->matchCallParam($call, $param, $scope);
if (! $callParam instanceof Param) {
return null;
}
return $callParam->type;
}
public function matchCallParam(StaticCall | MethodCall | FuncCall $call, Param $param, Scope $scope): ?Param
{
$callArgPosition = $this->matchCallArgPosition($call, $param);
if ($callArgPosition === null) {
return null;
}
$classMethodOrFunction = $this->astResolver->resolveClassMethodOrFunctionFromCall($call, $scope);
if ($classMethodOrFunction === null) {
return null;
}
return $classMethodOrFunction->params[$callArgPosition] ?? null;
}
public function matchParentParam(StaticCall $parentStaticCall, Param $param, Scope $scope): ?Param
{
$methodName = $this->nodeNameResolver->getName($parentStaticCall->name);
@ -29,7 +65,7 @@ final class ParentParamMatcher
}
// match current param to parent call position
$parentStaticCallArgPosition = $this->matchParentStaticCallArgPosition($parentStaticCall, $param);
$parentStaticCallArgPosition = $this->matchCallArgPosition($parentStaticCall, $param);
if ($parentStaticCallArgPosition === null) {
return null;
}
@ -37,11 +73,11 @@ final class ParentParamMatcher
return $this->resolveParentMethodParam($scope, $methodName, $parentStaticCallArgPosition);
}
private function matchParentStaticCallArgPosition(StaticCall $parentStaticCall, Param $param): int | null
private function matchCallArgPosition(StaticCall | MethodCall | FuncCall $call, Param $param): int | null
{
$paramName = $this->nodeNameResolver->getName($param);
foreach ($parentStaticCall->args as $argPosition => $arg) {
foreach ($call->args as $argPosition => $arg) {
if (! $arg->value instanceof Variable) {
continue;
}
@ -58,15 +94,17 @@ final class ParentParamMatcher
private function resolveParentMethodParam(Scope $scope, string $methodName, int $paramPosition): ?Param
{
/** @var ClassReflection $classReflection */
$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return null;
}
foreach ($classReflection->getParents() as $parnetClassReflection) {
if (! $parnetClassReflection->hasMethod($methodName)) {
foreach ($classReflection->getParents() as $parentClassReflection) {
if (! $parentClassReflection->hasMethod($methodName)) {
continue;
}
$parentClassMethod = $this->astResolver->resolveClassMethod($parnetClassReflection->getName(), $methodName);
$parentClassMethod = $this->astResolver->resolveClassMethod($parentClassReflection->getName(), $methodName);
if (! $parentClassMethod instanceof ClassMethod) {
continue;
}

View File

@ -0,0 +1,212 @@
<?php
declare(strict_types=1);
namespace Rector\TypeDeclaration\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\UnionType;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\TypeDeclaration\NodeAnalyzer\CallerParamMatcher;
use Symplify\Astral\NodeTraverser\SimpleCallableNodeTraverser;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamTypeByMethodCallTypeRector\ParamTypeByMethodCallTypeRectorTest
*/
final class ParamTypeByMethodCallTypeRector extends AbstractRector
{
public function __construct(
private CallerParamMatcher $callerParamMatcher,
private SimpleCallableNodeTraverser $simpleCallableNodeTraverser
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change param type based on passed method call type', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeTypedService
{
public function run(string $name)
{
}
}
final class UseDependency
{
public function __construct(
private SomeTypedService $someTypedService
) {
}
public function go($value)
{
$this->someTypedService->run($value);
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeTypedService
{
public function run(string $name)
{
}
}
final class UseDependency
{
public function __construct(
private SomeTypedService $someTypedService
) {
}
public function go(string $value)
{
$this->someTypedService->run($value);
}
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
if ($this->shouldSkipClassMethod($node)) {
return null;
}
/** @var array<StaticCall|MethodCall|FuncCall> $callers */
$callers = $this->betterNodeFinder->findInstancesOf(
(array) $node->stmts,
[StaticCall::class, MethodCall::class, FuncCall::class]
);
$hasChanged = false;
$scope = $node->getAttribute(AttributeKey::SCOPE);
foreach ($node->params as $param) {
if ($this->shouldSkipParam($param, $node)) {
continue;
}
foreach ($callers as $caller) {
$paramType = $this->callerParamMatcher->matchCallParamType($caller, $param, $scope);
if ($paramType === null) {
continue;
}
$this->mirrorParamType($param, $paramType);
$hasChanged = true;
}
}
if ($hasChanged) {
return $node;
}
return null;
}
private function shouldSkipClassMethod(ClassMethod $classMethod): bool
{
if ($classMethod->params === []) {
return true;
}
$scope = $classMethod->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return true;
}
$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return true;
}
return ! $classReflection->isClass();
}
private function mirrorParamType(
Param $decoratedParam,
Identifier | Name | NullableType | UnionType $paramType
): void {
// mimic type
$newParamType = $paramType;
$this->simpleCallableNodeTraverser->traverseNodesWithCallable(
$newParamType,
function (Node $node): void {
// original attributes have to removed to avoid tokens crashing from origin positions
$node->setAttributes([]);
}
);
$decoratedParam->type = $newParamType;
}
/**
* Should skip param because one of them is conditional types?
*/
private function isParamConditioned(Param $param, ClassMethod $classMethod): bool
{
$paramName = $this->nodeNameResolver->getName($param->var);
if ($paramName === null) {
return false;
}
/** @var Variable[] $variables */
$variables = $this->betterNodeFinder->findInstanceOf((array) $classMethod->stmts, Variable::class);
foreach ($variables as $variable) {
if (! $this->isName($variable, $paramName)) {
continue;
}
$conditional = $this->betterNodeFinder->findParentType($variable, If_::class);
if ($conditional instanceof If_) {
return true;
}
}
return false;
}
private function shouldSkipParam(Param $param, ClassMethod $classMethod): bool
{
if ($this->isParamConditioned($param, $classMethod)) {
return true;
}
// already has type, skip
return $param->type !== null;
}
}

View File

@ -12,7 +12,7 @@ use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\TypeDeclaration\NodeAnalyzer\ParentParamMatcher;
use Rector\TypeDeclaration\NodeAnalyzer\CallerParamMatcher;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -22,7 +22,7 @@ use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
final class ParamTypeByParentCallTypeRector extends AbstractRector
{
public function __construct(
private ParentParamMatcher $parentParamMatcher
private CallerParamMatcher $callerParamMatcher
) {
}
@ -90,8 +90,10 @@ CODE_SAMPLE
return null;
}
/** @var Scope $scope */
$scope = $node->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return null;
}
$hasChanged = false;
@ -101,7 +103,7 @@ CODE_SAMPLE
continue;
}
$parentParam = $this->parentParamMatcher->matchParentParam($parentStaticCall, $param, $scope);
$parentParam = $this->callerParamMatcher->matchParentParam($parentStaticCall, $param, $scope);
if (! $parentParam instanceof Param) {
continue;
}

View File

@ -5,6 +5,8 @@ declare(strict_types=1);
namespace Rector\Core\PhpParser;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Param;
@ -18,6 +20,7 @@ use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\NodeFinder;
use PhpParser\Parser;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\Php\PhpFunctionReflection;
@ -133,6 +136,17 @@ final class AstResolver
return $classMethod;
}
public function resolveClassMethodOrFunctionFromCall(
FuncCall | StaticCall | MethodCall $call,
Scope $scope
): ClassMethod | Function_ | null {
if ($call instanceof FuncCall) {
return $this->resolveFunctionFromFuncCall($call, $scope);
}
return $this->resolveClassMethodFromCall($call);
}
public function resolveFunctionFromFunctionReflection(PhpFunctionReflection $phpFunctionReflection): ?Function_
{
if (isset($this->functionsByName[$phpFunctionReflection->getName()])) {
@ -370,4 +384,22 @@ final class AstResolver
return null;
}
private function resolveFunctionFromFuncCall(FuncCall $funcCall, Scope $scope): ?Function_
{
if ($funcCall->name instanceof Expr) {
return null;
}
if (! $this->reflectionProvider->hasFunction($funcCall->name, $scope)) {
return null;
}
$reflectionFunction = $this->reflectionProvider->getFunction($funcCall->name, $scope);
if (! $reflectionFunction instanceof PhpFunctionReflection) {
return null;
}
return $this->resolveFunctionFromFunctionReflection($reflectionFunction);
}
}

View File

@ -341,14 +341,6 @@ final class NodeFactory
return $property;
}
/**
* @param mixed $value
*/
public function createClassConst(string $name, $value, int $modifier): ClassConst
{
return $this->createClassConstant($name, $value, $modifier);
}
public function createGetterClassMethod(string $propertyName, Type $type): ClassMethod
{
$methodBuilder = new MethodBuilder('get' . ucfirst($propertyName));
@ -571,19 +563,16 @@ final class NodeFactory
return $this->createBooleanAndFromNodes($newNodes);
}
/**
* @param mixed $value
*/
public function createClassConstant(string $name, $value, int $modifier): ClassConst
public function createClassConstant(string $name, Expr $expr, int $modifier): ClassConst
{
$value = BuilderHelpers::normalizeValue($value);
$expr = BuilderHelpers::normalizeValue($expr);
$const = new Const_($name, $value);
$const = new Const_($name, $expr);
$classConst = new ClassConst([$const]);
$classConst->flags |= $modifier;
// add @var type by default
$staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($value);
$staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($expr);
if (! $staticType instanceof MixedType) {
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($classConst);