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\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector;

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

final class AddParamArrayDocblockBasedOnArrayMapRectorTest 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,33 @@
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector\Fixture;

final class OverrideMixedType
{
/**
* @param mixed[] $items
*/
public function run(array $items): void
{
array_map(fn (string $item) => trim($item), $items);
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector\Fixture;

final class OverrideMixedType
{
/**
* @param string[] $items
*/
public function run(array $items): void
{
array_map(fn (string $item) => trim($item), $items);
}
}

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

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector\Fixture;

final class SkipBetterExistingType
{
/**
* @param array<string|\Stringable> $items
*/
public function run(array $items): void
{
array_map(fn (string $item) => trim($item), $items);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector\Fixture;

final class SomeClass
{
public function run(array $items): void
{
array_map(fn (string $item) => trim($item), $items);
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector\Fixture;

final class SomeClass
{
/**
* @param string[] $items
*/
public function run(array $items): void
{
array_map(fn (string $item) => trim($item), $items);
}
}

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

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector;

return RectorConfig::configure()
->withRules([AddParamArrayDocblockBasedOnArrayMapRector::class]);
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ public function shouldSkip(File $file, FullyQualifiedObjectType $fullyQualifiedO
* on php 7.x, substr() result can return false, so force (string) is needed
* @see https://github.com/rectorphp/rector-src/pull/7436
*/
$subClassName = (string) substr($fullyQualifiedObjectType->getClassName(), 0, -strlen($fullyQualifiedObjectType->getShortName()) - 1);
$subClassName = (string) substr(
$fullyQualifiedObjectType->getClassName(),
0,
-strlen($fullyQualifiedObjectType->getShortName()) - 1
);
$fullyQualifiedObjectTypeNamespace = strtolower($subClassName);

foreach ($classLikeNames as $classLikeName) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclarationDocblocks\NodeFinder;

use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\PhpParser\Node\BetterNodeFinder;

final readonly class ArrayMapClosureExprFinder
{
public function __construct(
private BetterNodeFinder $betterNodeFinder,
private NodeNameResolver $nodeNameResolver,
) {
}

/**
* @return array<Closure|ArrowFunction>
*/
public function findByVariableName(ClassMethod|Function_ $functionLike, string $variableName): array
{
if ($functionLike->stmts === null) {
return [];
}

/** @var FuncCall[] $funcCalls */
$funcCalls = $this->betterNodeFinder->findInstancesOfScoped($functionLike->stmts, FuncCall::class);

$arrayMapClosures = [];

foreach ($funcCalls as $funcCall) {
if ($funcCall->isFirstClassCallable()) {
continue;
}

if (! $this->nodeNameResolver->isName($funcCall, 'array_map')) {
continue;
}

$secondArg = $funcCall->getArgs()[1];
if (! $secondArg->value instanceof Variable) {
continue;
}

if (! $this->nodeNameResolver->isName($secondArg->value, $variableName)) {
continue;
}

$firstArg = $funcCall->getArgs()[0];
if (! $firstArg->value instanceof Closure && ! $firstArg->value instanceof ArrowFunction) {
continue;
}

$arrayMapClosures[] = $firstArg->value;
}

return $arrayMapClosures;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<?php

declare(strict_types=1);

namespace Rector\TypeDeclarationDocblocks\Rector\ClassMethod;

use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PHPStan\Type\ArrayType;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\Comments\NodeDocBlock\DocBlockUpdater;
use Rector\Rector\AbstractRector;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\TypeDeclarationDocblocks\NodeFinder\ArrayMapClosureExprFinder;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\TypeDeclarationDocblocks\Rector\ClassMethod\AddParamArrayDocblockBasedOnArrayMapRector\AddParamArrayDocblockBasedOnArrayMapRectorTest
*/
final class AddParamArrayDocblockBasedOnArrayMapRector extends AbstractRector
{
public function __construct(
private readonly ArrayMapClosureExprFinder $arrayMapClosureExprFinder,
private readonly StaticTypeMapper $staticTypeMapper,
private readonly PhpDocInfoFactory $phpDocInfoFactory,
private readonly DocBlockUpdater $docBlockUpdater,
private readonly PhpDocTypeChanger $phpDocTypeChanger,
) {

}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Add @param array docblock if array_map is used on the parameter', [
new CodeSample(
<<<'CODE_SAMPLE'
final class SomeClass
{
public function run(array $names): void
{
$names = array_map(fn(string $name) => trim($name), $names);
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
final class SomeClass
{
/**
* @param string[] $names
*/
public function run(array $names): void
{
$names = array_map(fn(string $name) => trim($name), $names);
}
}
CODE_SAMPLE
),
]);
}

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

/**
* @param ClassMethod|Function_ $node
*/
public function refactor(Node $node): ?Node
{
if ($node->getParams() === []) {
return null;
}

$hasChanged = false;
$functionPhpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);

foreach ($node->params as $param) {
// handle only arrays
if (! $this->isArrayParam($param)) {
continue;
}

$paramName = $this->getName($param);

$arrayMapClosures = $this->arrayMapClosureExprFinder->findByVariableName($node, $paramName);
if ($arrayMapClosures === []) {
continue;
}

foreach ($arrayMapClosures as $arrayMapClosure) {
$params = $arrayMapClosure->getParams();
if ($params === []) {
continue;
}

$firstParam = $params[0];
$paramTypeNode = $firstParam->type;
if ($paramTypeNode === null) {
continue;
}

$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($paramTypeNode);
$arrayParamType = new ArrayType(new MixedType(), $paramType);

if ($this->isAlreadyNonMixedParamType($functionPhpDocInfo, $paramName)) {
continue;
}

$this->phpDocTypeChanger->changeParamType(
$node,
$functionPhpDocInfo,
$arrayParamType,
$param,
$paramName
);
$hasChanged = true;
}

}

if (! $hasChanged) {
return null;
}

$this->docBlockUpdater->updateRefactoredNodeWithPhpDocInfo($node);

return $node;
}

private function isArrayParam(Param $param): bool
{
if (! $param->type instanceof Identifier) {
return false;
}

return $this->isName($param->type, 'array');
}

private function isMixedArrayType(Type $type): bool
{
if (! $type instanceof ArrayType) {
return false;
}

if (! $type->getItemType() instanceof MixedType) {
return false;
}

return $type->getKeyType() instanceof MixedType;
}

private function isAlreadyNonMixedParamType(
PhpDocInfo $functionPhpDocInfo,
string $paramName
): bool {
$currentParamType = $functionPhpDocInfo->getParamType($paramName);
if ($currentParamType instanceof MixedType) {
return false;
}

// has useful param type already?
return ! $this->isMixedArrayType($currentParamType);
}
}
2 changes: 1 addition & 1 deletion src/Config/Level/DeadCodeLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnExprInConstructRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnTagRector;
use Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector;
use Rector\DeadCode\Rector\Closure\RemoveUnusedClosureVariableUseRector;
use Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector;
use Rector\DeadCode\Rector\ConstFetch\RemovePhpVersionIdCheckRector;
use Rector\DeadCode\Rector\Expression\RemoveDeadStmtRector;
use Rector\DeadCode\Rector\Expression\SimplifyMirrorAssignRector;
Expand Down
Loading