Passed
Push — main ( 35cea8...263c2f )
by Andrey
21:51 queued 20:06
created

Castable   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 51
ccs 23
cts 23
cp 1
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 152
    protected function cast(array &$source)
13
    {
14 152
        foreach ($source as $key => &$value) {
15 150
            $value = $this->castValue($key, $value);
16
        }
17 152
    }
18
19 174
    protected function castValue(string $key, $value)
20
    {
21 174
        $cast = $this->castKey($key);
22
23 174
        $method = $this->castMethodName($cast);
24
25 174
        return $this->{$method}($value);
26
    }
27
28 174
    protected function castKey(string $key): string
29
    {
30 174
        return $this->casts[$key] ?? 'string';
31
    }
32
33 174
    protected function castMethodName(string $key): string
34
    {
35 174
        return (string) Str::of($key)->start('castTo_')->camel();
36
    }
37
38 70
    protected function castToArray($value): array
39
    {
40 70
        if (empty($value)) {
41 10
            return [];
42
        }
43
44 62
        if (is_array($value)) {
45 16
            return $value;
46
        }
47
48 53
        parse_str($value, $output);
49
50 53
        return $output;
51
    }
52
53 55
    protected function castToInteger($value): ?int
54
    {
55 55
        return empty($value) && ! is_numeric($value) ? null : $value;
56
    }
57
58 166
    protected function castToString(?string $value): string
59
    {
60 166
        return (string) $value;
61
    }
62
}
63