1: | <?php declare(strict_types = 1); |
2: | |
3: | namespace PHPStan\Type; |
4: | |
5: | use PHPStan\Type\Constant\ConstantArrayTypeBuilder; |
6: | use PHPStan\Type\Constant\ConstantBooleanType; |
7: | use PHPStan\Type\Constant\ConstantFloatType; |
8: | use PHPStan\Type\Constant\ConstantIntegerType; |
9: | use PHPStan\Type\Constant\ConstantStringType; |
10: | use PHPStan\Type\Enum\EnumCaseObjectType; |
11: | use UnitEnum; |
12: | use function count; |
13: | use function function_exists; |
14: | use function get_class; |
15: | use function is_array; |
16: | use function is_bool; |
17: | use function is_float; |
18: | use function is_int; |
19: | use function is_nan; |
20: | use function is_object; |
21: | use function is_string; |
22: | |
23: | |
24: | |
25: | |
26: | |
27: | class ConstantTypeHelper |
28: | { |
29: | |
30: | |
31: | |
32: | |
33: | |
34: | public static function getTypeFromValue($value): Type |
35: | { |
36: | if (is_int($value)) { |
37: | return new ConstantIntegerType($value); |
38: | } elseif (is_float($value)) { |
39: | if (is_nan($value)) { |
40: | return new MixedType(); |
41: | } |
42: | return new ConstantFloatType($value); |
43: | } elseif (is_bool($value)) { |
44: | return new ConstantBooleanType($value); |
45: | } elseif ($value === null) { |
46: | return new NullType(); |
47: | } elseif (is_string($value)) { |
48: | return new ConstantStringType($value); |
49: | } elseif (is_array($value)) { |
50: | $arrayBuilder = ConstantArrayTypeBuilder::createEmpty(); |
51: | if (count($value) > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) { |
52: | $arrayBuilder->degradeToGeneralArray(true); |
53: | } |
54: | foreach ($value as $k => $v) { |
55: | $arrayBuilder->setOffsetValueType(self::getTypeFromValue($k), self::getTypeFromValue($v)); |
56: | } |
57: | return $arrayBuilder->getArray(); |
58: | } elseif (is_object($value)) { |
59: | $class = get_class($value); |
60: | |
61: | if (function_exists('enum_exists') && \enum_exists($class)) { |
62: | |
63: | return new EnumCaseObjectType($class, $value->name); |
64: | } |
65: | |
66: | |
67: | return new ObjectType(get_class($value)); |
68: | } |
69: | |
70: | return new MixedType(); |
71: | } |
72: | |
73: | } |
74: | |