Passed
Push — master ( 54d817...889309 )
by Enjoys
02:29
created

ValueTypeCasting::castType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace Enjoys\Dotenv;
7
8
9
use Enjoys\Dotenv\Types\BoolType;
10
use Enjoys\Dotenv\Types\FalseType;
11
use Enjoys\Dotenv\Types\FloatType;
12
use Enjoys\Dotenv\Types\Int16Type;
13
use Enjoys\Dotenv\Types\Int8Type;
14
use Enjoys\Dotenv\Types\IntType;
15
use Enjoys\Dotenv\Types\NullType;
16
use Enjoys\Dotenv\Types\StringType;
17
use Enjoys\Dotenv\Types\TrueType;
18
use Enjoys\Dotenv\Types\TypeCastInterface;
19
20
final class ValueTypeCasting
21
{
22
23
    private const DEFINABLE_TYPES_MAP = [
24
        IntType::class,
25
        FloatType::class,
26
        TrueType::class,
27
        FalseType::class,
28
        NullType::class,
29
        BoolType::class,
30
        StringType::class,
31
        Int8Type::class,
32
        Int16Type::class
33
    ];
34
35
    private float|bool|int|string|null $castedValue;
36
37 34
    public function __construct(private string $originalValue)
38
    {
39 34
        $this->castedValue = $this->originalValue;
40 34
        $this->determine();
41
    }
42
43 12
    public static function castType(string|bool|int|float|null $value): string|bool|int|float|null
44
    {
45 12
        if (gettype($value) !== 'string') {
46
            return $value;
47
        }
48 12
        return (new self($value))->getCastValue();
49
    }
50
51 34
    public function getCastValue(): float|bool|int|string|null
52
    {
53 34
        return $this->castedValue;
54
    }
55
56 34
    private function determine(): void
57
    {
58 34
         foreach (self::DEFINABLE_TYPES_MAP as $typeClass) {
59
             /** @var TypeCastInterface $type */
60 34
             $type = new $typeClass($this->originalValue);
61 34
            if ($type->isPossible()){
62 24
                $this->castedValue = $type->getCastedValue();
63 24
                break;
64
            }
65
        }
66
    }
67
68
69
70
}
71