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