Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds AddClosureParamTypeFromObjectRector #6265

Merged
Show file tree
Hide file tree
Changes from all commits
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

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class AddClosureParamTypeFromObjectRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;

SimpleContainer::someCall(true, function ($object) {
return $object;
});

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;

SimpleContainer::someCall(true, function (\Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer $object) {
return $object;
});

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

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;
use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SomeType;

SimpleContainer::someCall(SomeType::class, fn(object $var) => $var);

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;
use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SomeType;

SimpleContainer::someCall(SomeType::class, fn(\Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer $var) => $var);

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

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;

SimpleContainer::someCall(anotherCallback: fn ($var) => $var, callback: fn($var) => $var);
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;

SimpleContainer::someCall(fn() => 'test');
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;

SimpleContainer::someCall('test');
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\NonTargetedClass;

NonTargetedClass::someCall(function ($name) {
return $name;
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Fixture;

use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;

SimpleContainer::someOtherCall(function ($name) {
return $name;
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source;

class NonTargetedClass
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source;

final class SimpleContainer
{

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

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\Source\SimpleContainer;
use Rector\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector;
use Rector\TypeDeclaration\ValueObject\AddClosureParamTypeFromObject;
use Rector\ValueObject\PhpVersionFeature;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig
->ruleWithConfiguration(AddClosureParamTypeFromObjectRector::class, [
new AddClosureParamTypeFromObject(SimpleContainer::class, 'someCall', 1, 0),
]);

$rectorConfig->phpVersion(PhpVersionFeature::MIXED_TYPE);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclaration\Rector\FunctionLike;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PHPStan\Type\ObjectType;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\NodeTypeResolver\TypeComparator\TypeComparator;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\Rector\AbstractRector;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\TypeDeclaration\ValueObject\AddClosureParamTypeFromObject;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Webmozart\Assert\Assert;

/**
* @see \Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeFromObjectRector\AddClosureParamTypeFromObjectRectorTest
*/
final class AddClosureParamTypeFromObjectRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @var int
*/
private const DEFAULT_CLOSURE_ARG_POSITION = 0;

/**
* @var AddClosureParamTypeFromObject[]
*/
private array $addClosureParamTypeFromObjects = [];

public function __construct(
private readonly TypeComparator $typeComparator,
private readonly StaticTypeMapper $staticTypeMapper
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Add closure param type based on the object of the method call', [
new ConfiguredCodeSample(
<<<'CODE_SAMPLE'
$request = new Request();
$request->when(true, function ($request) {});
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$request = new Request();
$request->when(true, function (Request $request) {});
CODE_SAMPLE
,
[new AddClosureParamTypeFromObject('Request', 'when', 1, 0)]
),
]);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [MethodCall::class, StaticCall::class];
}

/**
* @param MethodCall|StaticCall $node
*/
public function refactor(Node $node): ?Node
{
foreach ($this->addClosureParamTypeFromObjects as $addClosureParamTypeFromObject) {
if ($node instanceof MethodCall) {
$caller = $node->var;
} elseif ($node instanceof StaticCall) {
$caller = $node->class;
} else {
continue;
}

if (! $this->isCallMatch($caller, $addClosureParamTypeFromObject, $node)) {
continue;
}

$type = $this->getType($caller);
if (! $type instanceof ObjectType) {
continue;
}

return $this->processCallLike($node, $addClosureParamTypeFromObject, $type);
}

return null;
}

/**
* @param mixed[] $configuration
*/
public function configure(array $configuration): void
{
Assert::allIsAOf($configuration, AddClosureParamTypeFromObject::class);

$this->addClosureParamTypeFromObjects = $configuration;
}

private function processCallLike(
MethodCall|StaticCall $callLike,
AddClosureParamTypeFromObject $addClosureParamTypeFromArg,
ObjectType $objectType
): MethodCall|StaticCall|null {
if ($callLike->isFirstClassCallable()) {
return null;
}

$callLikeArg = $callLike->args[$addClosureParamTypeFromArg->getCallLikePosition()] ?? null;
if (! $callLikeArg instanceof Arg) {
return null;
}

// int positions shouldn't have names
if ($callLikeArg->name instanceof Identifier) {
return null;
}

$functionLike = $callLikeArg->value;
if (! $functionLike instanceof Closure && ! $functionLike instanceof ArrowFunction) {
return null;
}

if (! isset($functionLike->params[$addClosureParamTypeFromArg->getFunctionLikePosition()])) {
return null;
}

$callLikeArg = $callLike->getArgs()[self::DEFAULT_CLOSURE_ARG_POSITION] ?? null;
if (! $callLikeArg instanceof Arg) {
return null;
}

$hasChanged = $this->refactorParameter(
$functionLike->params[$addClosureParamTypeFromArg->getFunctionLikePosition()],
$objectType,
);

if ($hasChanged) {
return $callLike;
}

return null;
}

private function refactorParameter(Param $param, ObjectType $objectType): bool
{
// already set → no change
if ($param->type instanceof Node) {
$currentParamType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
if ($this->typeComparator->areTypesEqual($currentParamType, $objectType)) {
return false;
}
}

$paramTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($objectType, TypeKind::PARAM);
$param->type = $paramTypeNode;

return true;
}

private function isCallMatch(
Name|Expr $name,
AddClosureParamTypeFromObject $addClosureParamTypeFromArg,
StaticCall|MethodCall $call
): bool {
if (! $this->isObjectType($name, $addClosureParamTypeFromArg->getObjectType())) {
return false;
}

return $this->isName($call->name, $addClosureParamTypeFromArg->getMethodName());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclaration\ValueObject;

use PHPStan\Type\ObjectType;
use Rector\Validation\RectorAssert;

final readonly class AddClosureParamTypeFromObject
{
/**
* @param int<0, max> $callLikePosition
* @param int<0, max> $functionLikePosition
*/
public function __construct(
private string $className,
private string $methodName,
private int $callLikePosition,
private int $functionLikePosition,
) {
RectorAssert::className($className);
}

public function getObjectType(): ObjectType
{
return new ObjectType($this->className);
}

public function getMethodName(): string
{
return $this->methodName;
}

/**
* @return int<0, max>
*/
public function getCallLikePosition(): int
{
return $this->callLikePosition;
}

/**
* @return int<0, max>
*/
public function getFunctionLikePosition(): int
{
return $this->functionLikePosition;
}
}