Skip to content
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\ClassMethod\AddParamFromDimFetchKeyUseRector;

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

final class AddParamFromDimFetchKeyUseRectorTest 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,37 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\Fixture;

final class Fixture
{
public function process($key)
{
$items = [
'first' => 'Firstitem',
'second' => 'Seconditem',
];

return $items[$key];
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\Fixture;

final class Fixture
{
public function process(string $key)
{
$items = [
'first' => 'Firstitem',
'second' => 'Seconditem',
];

return $items[$key];
}
}

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

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\Fixture;

final class IntOrString
{
public function process($key)
{
$items = [
'first' => 'Firstitem',
111 => 'Seconditem',
'second' => 'Seconditem',
];

return $items[$key];
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\Fixture;

final class IntOrString
{
public function process(string|int $key)
{
$items = [
'first' => 'Firstitem',
111 => 'Seconditem',
'second' => 'Seconditem',
];

return $items[$key];
}
}

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

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\Fixture;

final class SkipExistingType
{
public function process(int $key): void
{
$items = [
'first' => 'Firstitem',
'second' => 'Seconditem',
];

return $items[$key];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\Fixture;

final class SkipUnclearType
{
public function process($key, $items)
{
return $items[$key];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(AddParamFromDimFetchKeyUseRector::class);
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

declare(strict_types=1);

use Rector\ValueObject\PhpVersionFeature;
use Rector\Config\RectorConfig;
use Rector\TypeDeclaration\Rector\ClassMethod\KnownMagicClassMethodTypeRector;
use Rector\ValueObject\PhpVersionFeature;

return RectorConfig::configure()
->withRules([KnownMagicClassMethodTypeRector::class])
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclaration\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\Rector\AbstractRector;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\TypeDeclarationDocblocks\NodeFinder\ArrayDimFetchFinder;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector\AddParamFromDimFetchKeyUseRectorTest
*/
final class AddParamFromDimFetchKeyUseRector extends AbstractRector
{
public function __construct(
private readonly ArrayDimFetchFinder $arrayDimFetchFinder,
private readonly StaticTypeMapper $staticTypeMapper
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Add method param type based on use in array dim fetch of known keys',
[
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
public function get($key)
{
$data = [
'name' => 'John',
'age' => 30,
];

return $data[$key];
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
public function get(string $key)
{
$data = [
'name' => 'John',
'age' => 30,
];

return $data[$key];
}
}
CODE_SAMPLE
),

]
);
}

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

/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
$hasChanged = false;

foreach ($node->getMethods() as $classMethod) {
if ($classMethod->params === []) {
continue;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parent guard check is needed here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

foreach ($classMethod->getParams() as $param) {
if ($param->type instanceof Node) {
continue;
}

/** @var string $paramName */
$paramName = $this->getName($param->var);

$dimFetches = $this->arrayDimFetchFinder->findByDimName($classMethod, $paramName);
if ($dimFetches === []) {
continue;
}

foreach ($dimFetches as $dimFetch) {
$dimFetchType = $this->getType($dimFetch->var);

if (! $dimFetchType instanceof ArrayType && ! $dimFetchType instanceof ConstantArrayType) {
continue;
}

$paramTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode(
$dimFetchType->getKeyType(),
TypeKind::PARAM
);

if (! $paramTypeNode instanceof Node) {
continue;
}

$param->type = $paramTypeNode;
$hasChanged = true;
}
}
}

if ($hasChanged) {
return $node;
}

return null;
}
}
16 changes: 16 additions & 0 deletions rules/TypeDeclarationDocblocks/NodeFinder/ArrayDimFetchFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,20 @@ public function findByVariableName(Node $node, string $variableName): array
return $this->nodeNameResolver->isName($arrayDimFetch->var, $variableName);
});
}

/**
* @return ArrayDimFetch[]
*/
public function findByDimName(ClassMethod $classMethod, string $dimName): array
{
$dimFetches = $this->betterNodeFinder->findInstancesOfScoped([$classMethod], ArrayDimFetch::class);

return array_filter($dimFetches, function (ArrayDimFetch $arrayDimFetch) use ($dimName): bool {
if (! $arrayDimFetch->dim instanceof Variable) {
return false;
}

return $this->nodeNameResolver->isName($arrayDimFetch->dim, $dimName);
});
}
}
3 changes: 3 additions & 0 deletions src/Config/Level/TypeDeclarationLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Rector\TypeDeclaration\Rector\Class_\TypedPropertyFromDocblockSetUpDefinedRector;
use Rector\TypeDeclaration\Rector\Class_\TypedPropertyFromJMSSerializerAttributeTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamFromDimFetchKeyUseRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeBasedOnPHPUnitDataProviderRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeFromPropertyTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationBasedOnParentClassMethodRector;
Expand Down Expand Up @@ -146,9 +147,11 @@ final class TypeDeclarationLevel

// array parameter from dim fetch assign inside
StrictArrayParamDimFetchRector::class,
AddParamFromDimFetchKeyUseRector::class,

// possibly based on docblocks, but also helpful, intentionally last
AddArrayFunctionClosureParamTypeRector::class,
TypedPropertyFromDocblockSetUpDefinedRector::class,

];
}