Skip to content

Commit 3b14af2

Browse files
authored
Type hint array reduce closure (#6725)
* Adds the AddClosureParamTypeForArrayReduceRector rule * Handles the initial value * Added to type hinting config
1 parent 3569d16 commit 3b14af2

File tree

7 files changed

+339
-0
lines changed

7 files changed

+339
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector;
6+
7+
use Iterator;
8+
use PHPUnit\Framework\Attributes\DataProvider;
9+
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
10+
11+
final class AddClosureParamTypeForArrayReduceRectorTest extends AbstractRectorTestCase
12+
{
13+
#[DataProvider('provideData')]
14+
public function test(string $filePath): void
15+
{
16+
$this->doTestFile($filePath);
17+
}
18+
19+
public static function provideData(): Iterator
20+
{
21+
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
22+
}
23+
24+
public function provideConfigFilePath(): string
25+
{
26+
return __DIR__ . '/config/configured_rule.php';
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector\Fixture;
4+
5+
class Fixture
6+
{
7+
/**
8+
* @param list<string> $array
9+
*/
10+
public function run(array $array)
11+
{
12+
return array_reduce($array, function ($carry, $value) {
13+
return $carry . $value;
14+
}, '');
15+
}
16+
17+
/**
18+
* @param list<string|int> $array
19+
*/
20+
public function runTwo(array $array)
21+
{
22+
return array_reduce($array, function ($carry, $value) {
23+
return $carry . $value;
24+
}, 100);
25+
}
26+
}
27+
28+
?>
29+
-----
30+
<?php
31+
32+
namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector\Fixture;
33+
34+
class Fixture
35+
{
36+
/**
37+
* @param list<string> $array
38+
*/
39+
public function run(array $array)
40+
{
41+
return array_reduce($array, function (string $carry, string $value) {
42+
return $carry . $value;
43+
}, '');
44+
}
45+
46+
/**
47+
* @param list<string|int> $array
48+
*/
49+
public function runTwo(array $array)
50+
{
51+
return array_reduce($array, function (int|string $carry, int|string $value) {
52+
return $carry . $value;
53+
}, 100);
54+
}
55+
}
56+
57+
?>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector\Fixture;
4+
5+
class SkipMixedType
6+
{
7+
/**
8+
* @param array<int, mixed> $array
9+
*/
10+
public function run(array $array)
11+
{
12+
return array_reduce($array, function ($carry, $value) {
13+
return $value->foo($carry);
14+
}, '');
15+
}
16+
17+
/**
18+
* @param array<int, mixed> $array
19+
*/
20+
public function runTwo(array $array, mixed $initial)
21+
{
22+
return array_reduce($array, function ($carry, $value) {
23+
return '';
24+
}, $initial);
25+
}
26+
}
27+
28+
?>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayMapRector\Fixture;
4+
5+
function array_reduce(array $array, callable $func, $initial = null): array
6+
{
7+
8+
}
9+
10+
class SkipNonArrayReduceFunctions
11+
{
12+
/**
13+
* @param array<int, string> $array
14+
*/
15+
public function run(array $array)
16+
{
17+
return \Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayMapRector\Fixture\array_reduce($array, function ($value, $key) {
18+
return $value . $key;
19+
});
20+
}
21+
}
22+
23+
?>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Rector\Config\RectorConfig;
6+
use Rector\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector;
7+
use Rector\ValueObject\PhpVersionFeature;
8+
9+
return static function (RectorConfig $rectorConfig): void {
10+
$rectorConfig
11+
->rules([AddClosureParamTypeForArrayReduceRector::class]);
12+
13+
$rectorConfig->phpVersion(PhpVersionFeature::UNION_TYPES);
14+
};
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rector\TypeDeclaration\Rector\FunctionLike;
6+
7+
use PhpParser\Node;
8+
use PhpParser\Node\Expr\Closure;
9+
use PhpParser\Node\Expr\FuncCall;
10+
use PhpParser\Node\Param;
11+
use PHPStan\Reflection\Native\NativeFunctionReflection;
12+
use PHPStan\Type\ClosureType;
13+
use PHPStan\Type\MixedType;
14+
use PHPStan\Type\Type;
15+
use PHPStan\Type\UnionType;
16+
use PHPStan\Type\UnionTypeHelper;
17+
use Rector\NodeTypeResolver\TypeComparator\TypeComparator;
18+
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
19+
use Rector\Rector\AbstractRector;
20+
use Rector\Reflection\ReflectionResolver;
21+
use Rector\StaticTypeMapper\StaticTypeMapper;
22+
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
23+
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
24+
25+
/**
26+
* @see \Rector\Tests\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector\AddClosureParamTypeForArrayReduceRectorTest
27+
*/
28+
final class AddClosureParamTypeForArrayReduceRector extends AbstractRector
29+
{
30+
public function __construct(
31+
private readonly TypeComparator $typeComparator,
32+
private readonly StaticTypeMapper $staticTypeMapper,
33+
private readonly ReflectionResolver $reflectionResolver,
34+
) {
35+
}
36+
37+
public function getRuleDefinition(): RuleDefinition
38+
{
39+
return new RuleDefinition(
40+
'Applies type hints to array_map closures',
41+
[
42+
new CodeSample(
43+
<<<'CODE_SAMPLE'
44+
array_reduce($strings, function ($carry, $value, $key): string {
45+
return $carry . $value;
46+
}, $initialString);
47+
CODE_SAMPLE
48+
,
49+
<<<'CODE_SAMPLE'
50+
array_reduce($strings, function (string $carry, string $value): string {
51+
return $carry . $value;
52+
}, $initialString);
53+
CODE_SAMPLE
54+
,
55+
),
56+
]
57+
);
58+
}
59+
60+
public function getNodeTypes(): array
61+
{
62+
return [FuncCall::class];
63+
}
64+
65+
/**
66+
* @param FuncCall $node
67+
*/
68+
public function refactor(Node $node): ?Node
69+
{
70+
if ($node->isFirstClassCallable()) {
71+
return null;
72+
}
73+
74+
if (! $this->isName($node, 'array_reduce')) {
75+
return null;
76+
}
77+
78+
$funcReflection = $this->reflectionResolver->resolveFunctionLikeReflectionFromCall($node);
79+
80+
if (! $funcReflection instanceof NativeFunctionReflection) {
81+
return null;
82+
}
83+
84+
$args = $node->getArgs();
85+
86+
if (! isset($args[1]) || ! $args[1]->value instanceof Closure) {
87+
return null;
88+
}
89+
90+
$closureType = $this->getType($args[1]->value);
91+
if (! $closureType instanceof ClosureType) {
92+
return null;
93+
}
94+
95+
$carryType = $closureType->getReturnType();
96+
97+
if (isset($args[2])) {
98+
$carryType = $this->combineTypes([$this->getType($args[2]->value), $carryType]);
99+
}
100+
101+
$type = $this->getType($args[0]->value);
102+
$valueType = $type->getIterableValueType();
103+
104+
if ($this->updateClosureWithTypes($args[1]->value, $valueType, $carryType)) {
105+
return $node;
106+
}
107+
108+
return null;
109+
}
110+
111+
private function updateClosureWithTypes(Closure $closure, ?Type $valueType, ?Type $carryType): bool
112+
{
113+
$changes = false;
114+
$carryParam = $closure->params[0] ?? null;
115+
$valueParam = $closure->params[1] ?? null;
116+
117+
if ($valueParam instanceof Param && $valueType instanceof Type && $this->refactorParameter(
118+
$valueParam,
119+
$valueType
120+
)) {
121+
$changes = true;
122+
}
123+
124+
if ($carryParam instanceof Param && $carryType instanceof Type && $this->refactorParameter(
125+
$carryParam,
126+
$carryType
127+
)) {
128+
return true;
129+
}
130+
131+
return $changes;
132+
}
133+
134+
private function refactorParameter(Param $param, Type $type): bool
135+
{
136+
if ($type instanceof MixedType) {
137+
return false;
138+
}
139+
140+
// already set → no change
141+
if ($param->type instanceof Node) {
142+
$currentParamType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
143+
if ($this->typeComparator->areTypesEqual($currentParamType, $type)) {
144+
return false;
145+
}
146+
}
147+
148+
$paramTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode($type, TypeKind::PARAM);
149+
150+
if (! $paramTypeNode instanceof Node) {
151+
return false;
152+
}
153+
154+
$param->type = $paramTypeNode;
155+
156+
return true;
157+
}
158+
159+
/**
160+
* @param Type[] $types
161+
*/
162+
private function combineTypes(array $types): ?Type
163+
{
164+
if ($types === []) {
165+
return null;
166+
}
167+
168+
$types = array_reduce($types, function (array $types, Type $type): array {
169+
foreach ($types as $previousType) {
170+
if ($this->typeComparator->areTypesEqual($type, $previousType)) {
171+
return $types;
172+
}
173+
}
174+
175+
$types[] = $type;
176+
return $types;
177+
}, []);
178+
179+
if (count($types) === 1) {
180+
return $types[0];
181+
}
182+
183+
return new UnionType(UnionTypeHelper::sortTypes($types));
184+
}
185+
}

src/Config/Level/TypeDeclarationLevel.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@
4949
use Rector\TypeDeclaration\Rector\Closure\ClosureReturnTypeRector;
5050
use Rector\TypeDeclaration\Rector\Empty_\EmptyOnNullableObjectToInstanceOfRector;
5151
use Rector\TypeDeclaration\Rector\Function_\AddFunctionVoidReturnTypeWhereNoReturnRector;
52+
use Rector\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayMapRector;
53+
use Rector\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector;
5254
use Rector\TypeDeclaration\Rector\FunctionLike\AddParamTypeSplFixedArrayRector;
5355
use Rector\TypeDeclaration\Rector\FunctionLike\AddReturnTypeDeclarationFromYieldsRector;
5456
use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector;
@@ -120,6 +122,8 @@ final class TypeDeclarationLevel
120122
// closures
121123
AddClosureNeverReturnTypeRector::class,
122124
ClosureReturnTypeRector::class,
125+
AddClosureParamTypeForArrayReduceRector::class,
126+
AddClosureParamTypeForArrayMapRector::class,
123127

124128
// more risky rules
125129
ReturnTypeFromStrictParamRector::class,

0 commit comments

Comments
 (0)