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

ValueTypeCasting   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
dl 0
loc 44
ccs 14
cts 15
cp 0.9333
rs 10
c 1
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A castType() 0 6 2
A determine() 0 8 3
A getCastValue() 0 3 1
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