Castable::castMethodName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
/*
3
 * This file is part of the "andrey-helldar/support" project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author Andrey Helldar <[email protected]>
9
 *
10
 * @copyright 2021 Andrey Helldar
11
 *
12
 * @license MIT
13
 *
14
 * @see https://github.com/andrey-helldar/support
15
 */
16
17
namespace Helldar\Support\Concerns;
18
19
use Helldar\Support\Facades\Helpers\Str;
20
21
/**
22
 * @property array $casts
23
 */
24
trait Castable
25
{
26 154
    protected function cast(array &$source)
27
    {
28 154
        foreach ($source as $key => &$value) {
29 152
            $value = $this->castValue($key, $value);
30
        }
31 154
    }
32
33 176
    protected function castValue(string $key, $value)
34
    {
35 176
        $cast = $this->castKey($key);
36
37 176
        $method = $this->castMethodName($cast);
38
39 176
        return $this->{$method}($value);
40
    }
41
42 176
    protected function castKey(string $key): string
43
    {
44 176
        return $this->casts[$key] ?? 'string';
45
    }
46
47 176
    protected function castMethodName(string $key): string
48
    {
49 176
        return (string) Str::of($key)->start('castTo_')->camel();
50
    }
51
52 72
    protected function castToArray($value): array
53
    {
54 72
        if (empty($value)) {
55 10
            return [];
56
        }
57
58 64
        if (is_array($value)) {
59 16
            return $value;
60
        }
61
62 55
        parse_str($value, $output);
63
64 55
        return $output;
65
    }
66
67 55
    protected function castToInteger($value): ?int
68
    {
69 55
        return empty($value) && ! is_numeric($value) ? null : $value;
70
    }
71
72 168
    protected function castToString(?string $value): string
73
    {
74 168
        return (string) $value;
75
    }
76
}
77