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: /** @api */
24: class ConstantTypeHelper
25: {
26:
27: /**
28: * @deprecated Use PHPStan\Reflection\InitializerExprTypeResolver
29: * @param mixed $value
30: */
31: public static function getTypeFromValue($value): Type
32: {
33: if (is_int($value)) {
34: return new ConstantIntegerType($value);
35: } elseif (is_float($value)) {
36: if (is_nan($value)) {
37: return new MixedType();
38: }
39: return new ConstantFloatType($value);
40: } elseif (is_bool($value)) {
41: return new ConstantBooleanType($value);
42: } elseif ($value === null) {
43: return new NullType();
44: } elseif (is_string($value)) {
45: return new ConstantStringType($value);
46: } elseif (is_array($value)) {
47: $arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
48: if (count($value) > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
49: $arrayBuilder->degradeToGeneralArray();
50: }
51: foreach ($value as $k => $v) {
52: $arrayBuilder->setOffsetValueType(self::getTypeFromValue($k), self::getTypeFromValue($v));
53: }
54: return $arrayBuilder->getArray();
55: } elseif (is_object($value)) {
56: $class = get_class($value);
57: /** phpcs:disable SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly.ReferenceViaFullyQualifiedName */
58: if (function_exists('enum_exists') && \enum_exists($class)) {
59: /** @var UnitEnum $value */
60: return new EnumCaseObjectType($class, $value->name);
61: }
62: /** phpcs:enable */
63:
64: return new ObjectType(get_class($value));
65: }
66:
67: return new MixedType();
68: }
69:
70: }
71: