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

ObjectConstructorTrait::__construct()   B

Complexity

Conditions 10
Paths 20

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 18
c 1
b 0
f 0
nc 20
nop 1
dl 0
loc 31
ccs 19
cts 19
cp 1
crap 10
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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