-
Notifications
You must be signed in to change notification settings - Fork 8
/
PropertyTypeFactory.php
94 lines (80 loc) · 2.66 KB
/
PropertyTypeFactory.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace ClassTransformer\Reflection\Types;
use ReflectionNamedType;
use ClassTransformer\TransformUtils;
use ClassTransformer\Enums\TypeEnums;
use ClassTransformer\Attributes\ConvertArray;
use ClassTransformer\Reflection\RuntimeReflectionProperty;
use ReflectionType;
/**
* Class PropertyTypeFactory
*
* @author yzen.dev <yzen.dev@gmail.com>
*/
class PropertyTypeFactory
{
/**
* @param RuntimeReflectionProperty $property
*
* @return ArrayType|EnumType|PropertyType|ScalarType|TransformableType
*/
public static function create(RuntimeReflectionProperty $property)
{
$reflectionType = $property->reflectionProperty->getType();
$type = TypeEnums::TYPE_MIXED;
$isScalar = true;
$isNullable = true;
if ($reflectionType instanceof ReflectionType) {
$type = (string)$reflectionType;
$isNullable = $reflectionType->allowsNull();
}
if ($reflectionType instanceof ReflectionNamedType) {
$type = $reflectionType->getName();
$isScalar = $reflectionType->isBuiltin();
$isNullable = $reflectionType->allowsNull();
}
if ($property->notTransform()) {
return new ScalarType(
$type,
$isScalar,
$isNullable
);
}
if ($type === TypeEnums::TYPE_ARRAY) {
$arrayTypeAttr = $property->getAttributeArguments(ConvertArray::class);
if ($arrayTypeAttr !== null && isset($arrayTypeAttr[0])) {
$arrayType = $arrayTypeAttr[0];
} else {
$arrayType = TransformUtils::getClassFromPhpDoc($property->getDocComment());
}
$arrayType ??= TypeEnums::TYPE_MIXED;
$typeInstance = new ArrayType(
$type,
$isScalar,
$isNullable
);
$typeInstance->itemsType = $arrayType ?? TypeEnums::TYPE_MIXED;
$typeInstance->isScalarItems = in_array($arrayType, [TypeEnums::TYPE_INTEGER, TypeEnums::TYPE_FLOAT, TypeEnums::TYPE_STRING, TypeEnums::TYPE_BOOLEAN, TypeEnums::TYPE_MIXED]);
return $typeInstance;
}
if ($isScalar) {
return new ScalarType(
$type,
$isScalar,
$isNullable
);
}
if (function_exists('enum_exists') && enum_exists($type)) {
return new EnumType(
$type,
$isScalar,
$isNullable
);
}
return new TransformableType(
$type,
$isScalar,
);
}
}