generated from php-standard-library/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
FunctionReturnTypeProvider.php
79 lines (63 loc) · 2.49 KB
/
FunctionReturnTypeProvider.php
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace Psl\Psalm\EventHandler\Iter\Count;
use Psalm\Plugin\EventHandler\Event\FunctionReturnTypeProviderEvent;
use Psalm\Plugin\EventHandler\FunctionReturnTypeProviderInterface;
use Psalm\Type;
use Psl\Psalm\Argument;
use function count;
final class FunctionReturnTypeProvider implements FunctionReturnTypeProviderInterface
{
/**
* @return non-empty-list<lowercase-string>
*/
public static function getFunctionIds(): array
{
return [
'psl\iter\count',
];
}
public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $event): ?Type\Union
{
$argument_type = Argument::getType($event->getCallArgs(), $event->getStatementsSource(), 0);
if (null === $argument_type) {
return Type::getInt();
}
$array_argument_type = $argument_type->getAtomicTypes()['array'] ?? null;
if (null === $array_argument_type) {
return Type::getInt();
}
// non-empty-array/non-empty-list -> positive-int / literal-int
if ($array_argument_type instanceof Type\Atomic\TNonEmptyList) {
$count = $array_argument_type->count;
if (null === $count) {
return new Type\Union([new Type\Atomic\TIntRange(1, null)]);
}
return Type::getInt(false, $count);
}
if ($array_argument_type instanceof Type\Atomic\TNonEmptyArray) {
$count = $array_argument_type->count;
if (null === $count) {
return new Type\Union([new Type\Atomic\TIntRange(1, null)]);
}
return Type::getInt(false, $count);
}
// array{foo: bar} -> literal-int(1)
if ($array_argument_type instanceof Type\Atomic\TKeyedArray) {
// Psalm allows extra properties in keyed arrays, so we can't return a literal integer
// for this.
//
// return Type::getInt(false, count($array_argument_type->properties));
if (count($array_argument_type->properties) >= 1) {
return new Type\Union([new Type\Atomic\TIntRange(1, null)]);
}
return Type::getInt();
}
if ($array_argument_type instanceof Type\Atomic\TArray) {
if ($array_argument_type->type_params[0]->isNever() && $array_argument_type->type_params[1]->isNever()) {
return Type::getInt(false, 0);
}
}
return Type::getInt();
}
}