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

Castable::cast()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
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