Passed
Pull Request — main (#138)
by Andrey
15:00
created

Castable   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 51
rs 10
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A castToString() 0 3 1
A castToInteger() 0 3 3
A castValue() 0 7 1
A cast() 0 4 2
A castMethodName() 0 3 1
A castToArray() 0 13 3
A castKey() 0 3 1
1
<?php
2
3
namespace Helldar\Support\Concerns;
4
5
use Helldar\Support\Facades\Helpers\Str;
6
7
/**
8
 * @property array $casts
9
 */
10
trait Castable
11
{
12
    protected function cast(array &$source)
13
    {
14
        foreach ($source as $key => &$value) {
15
            $value = $this->castValue($key, $value);
16
        }
17
    }
18
19
    protected function castValue(string $key, $value)
20
    {
21
        $cast = $this->castKey($key);
22
23
        $method = $this->castMethodName($cast);
24
25
        return $this->{$method}($value);
26
    }
27
28
    protected function castKey(string $key): string
29
    {
30
        return $this->casts[$key] ?? 'string';
31
    }
32
33
    protected function castMethodName(string $key): string
34
    {
35
        return (string) Str::of($key)->start('castTo_')->camel();
36
    }
37
38
    protected function castToArray($value): array
39
    {
40
        if (empty($value)) {
41
            return [];
42
        }
43
44
        if (is_array($value)) {
45
            return $value;
46
        }
47
48
        parse_str($value, $output);
49
50
        return $output;
51
    }
52
53
    protected function castToInteger($value): ?int
54
    {
55
        return empty($value) && ! is_numeric($value) ? null : $value;
56
    }
57
58
    protected function castToString(?string $value): string
59
    {
60
        return (string) $value;
61
    }
62
}
63