-
-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathNodeTypeCorrector.php
More file actions
59 lines (47 loc) · 1.85 KB
/
Copy pathNodeTypeCorrector.php
File metadata and controls
59 lines (47 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
declare(strict_types=1);
namespace Rector\NodeTypeResolver;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\Type;
use Rector\NodeTypeResolver\NodeTypeCorrector\AccessoryNonEmptyArrayTypeCorrector;
use Rector\NodeTypeResolver\NodeTypeCorrector\AccessoryNonEmptyStringTypeCorrector;
use Rector\NodeTypeResolver\NodeTypeCorrector\GenericClassStringTypeCorrector;
/**
* This service correct unnecessary intersection/union types that do not bring any value.
* We focus on scalar types like "array", "string", "int" etc.,
* to print them as valid type declarations.
*/
final readonly class NodeTypeCorrector
{
public function __construct(
private AccessoryNonEmptyStringTypeCorrector $accessoryNonEmptyStringTypeCorrector,
private GenericClassStringTypeCorrector $genericClassStringTypeCorrector,
private AccessoryNonEmptyArrayTypeCorrector $accessoryNonEmptyArrayTypeCorrector,
) {
}
public function correctType(Type $type): Type
{
$type = $this->accessoryNonEmptyStringTypeCorrector->correct($type);
$type = $this->genericClassStringTypeCorrector->correct($type);
$type = $this->removeAccessoryArrayListType($type);
return $this->accessoryNonEmptyArrayTypeCorrector->correct($type);
}
private function removeAccessoryArrayListType(Type $type): Type
{
if (! $type instanceof IntersectionType) {
return $type;
}
$cleanTypes = [];
foreach ($type->getTypes() as $intersectionType) {
if ($intersectionType instanceof AccessoryArrayListType) {
continue;
}
$cleanTypes[] = $intersectionType;
}
if (count($cleanTypes) === 1) {
return $cleanTypes[0];
}
return new IntersectionType($cleanTypes);
}
}