Passed
Push — master ( 18efe9...9cdba3 )
by George
04:43
created

ObjectConstructorTrait   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 38
ccs 19
cts 19
cp 1
rs 10
wmc 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 31 10
1
<?php
2
3
namespace ag84ark\ObjectConvertor;
4
5
use Illuminate\Support\Str;
6
7
trait ObjectConstructorTrait
8
{
9
    /**
10
     * ObjectConstructorTrait constructor.
11
     *
12
     * @param array|string|object $array
13
     */
14 44
    public function __construct($array = [])
15
    {
16 44
        if (is_string($array)) {
17 2
            $array = json_decode($array, true);
18
        }
19 44
        if (is_object($array)) {
20 2
            $array = $array->toArray() ?? (array) $array;
21
        }
22
23 44
        $methods = get_class_methods(self::class);
24
25 44
        foreach ($methods as $method) {
26 44
            preg_match('/^(set)(.*?)$/i', $method, $results);
27
28 44
            $pre = $results[1] ?? '';
29
30 44
            $k = $results[2] ?? '';
31
32 44
            $k = strtolower(substr($k, 0, 1)).substr($k, 1);
33 44
            $k2 = Str::snake($k);
34
35 44
            if ('set' === $pre && ! empty($array[$k])) {
36 18
                $this->$method($array[$k]);
37 44
            } elseif ('set' === $pre && ! empty($array[$k2])) {
38 4
                $this->$method($array[$k2]);
39 44
            } elseif ('set' === $pre && ! empty($array[Str::ucfirst($k)])) {
40 22
                $this->$method($array[Str::ucfirst($k)]);
41
            }
42
        }
43
44 44
        return $this;
45
    }
46
}
47