Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
80.00% |
24 / 30 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
| ScalarType | |
80.00% |
24 / 30 |
|
50.00% |
2 / 4 |
19.31 | |
0.00% |
0 / 1 |
| createFromReflectionType | |
82.35% |
14 / 17 |
|
0.00% |
0 / 1 |
9.45 | |||
| toReflectionType | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| toDoctrineType | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| toJsonSchemaType | |
66.67% |
6 / 9 |
|
0.00% |
0 / 1 |
5.93 | |||
| 1 | <?php |
| 2 | namespace Apie\Core\Enums; |
| 3 | |
| 4 | use Apie\TypeConverter\ReflectionTypeFactory; |
| 5 | use ReflectionIntersectionType; |
| 6 | use ReflectionNamedType; |
| 7 | use ReflectionType; |
| 8 | use ReflectionUnionType; |
| 9 | use stdClass; |
| 10 | |
| 11 | enum ScalarType: string |
| 12 | { |
| 13 | case STRING = 'string'; |
| 14 | case FLOAT = 'float'; |
| 15 | case INTEGER = 'int'; |
| 16 | case NULLVALUE = 'null'; |
| 17 | case ARRAY = 'array'; |
| 18 | case BOOLEAN = 'bool'; |
| 19 | case MIXED = 'mixed'; |
| 20 | case STDCLASS = stdClass::class; |
| 21 | |
| 22 | public const PRIMITIVES = [self::STRING, self::FLOAT, self::INTEGER, self::BOOLEAN]; |
| 23 | |
| 24 | public static function createFromReflectionType(?ReflectionType $type, bool $ignoreNull): ScalarType |
| 25 | { |
| 26 | if ($type === null) { |
| 27 | return self::MIXED; |
| 28 | } |
| 29 | if ($type instanceof ReflectionIntersectionType) { |
| 30 | return self::STDCLASS; |
| 31 | } |
| 32 | if ($type instanceof ReflectionUnionType) { |
| 33 | $current = null; |
| 34 | foreach ($type->getTypes() as $subType) { |
| 35 | $subScalar = self::createFromReflectionType($subType, $ignoreNull); |
| 36 | if ($current === null) { |
| 37 | if ($subScalar === self::NULLVALUE && $ignoreNull) { |
| 38 | continue; |
| 39 | } |
| 40 | $current = $subScalar; |
| 41 | } elseif ($current !== $subScalar) { |
| 42 | return self::MIXED; |
| 43 | } |
| 44 | } |
| 45 | return $current ?? self::NULLVALUE; |
| 46 | } |
| 47 | assert($type instanceof ReflectionNamedType); |
| 48 | |
| 49 | return self::tryFrom($type->getName()) ?? self::MIXED; |
| 50 | } |
| 51 | |
| 52 | public function toReflectionType(): ReflectionType |
| 53 | { |
| 54 | return ReflectionTypeFactory::createReflectionType($this->value); |
| 55 | } |
| 56 | |
| 57 | public function toDoctrineType(): string |
| 58 | { |
| 59 | if ($this === self::INTEGER) { |
| 60 | return 'integer'; |
| 61 | } |
| 62 | return $this->value; |
| 63 | } |
| 64 | |
| 65 | public function toJsonSchemaType(): string |
| 66 | { |
| 67 | if ($this === self::INTEGER) { |
| 68 | return 'integer'; |
| 69 | } |
| 70 | if ($this === self::FLOAT) { |
| 71 | return 'number'; |
| 72 | } |
| 73 | if ($this === self::BOOLEAN) { |
| 74 | return 'boolean'; |
| 75 | } |
| 76 | if ($this === self::STDCLASS) { |
| 77 | return 'object'; |
| 78 | } |
| 79 | return $this->value; |
| 80 | } |
| 81 | } |