Completed
Push — master ( 427685...52c844 )
by Alex Ribeiro de
24s queued 11s
created

ResourceContract::arrayIndexToCamelCase()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
4
namespace Hell\Vephar\Contracts;
5
6
use Hell\Vephar\Response;
7
8
abstract class ResourceContract
9
{
10
11
12
    /**
13
     * ResourceContract constructor.
14
     * @param $data
15
     * @param bool $setters
16
     */
17 18
    public function __construct($data, $setters = true)
18
    {
19 18
        if ($setters) {
20 6
            $this->bySetMethod($data);
21 6
            return;
22
        }
23 18
        $this->byDinamicallyAttribute($data);
24 18
        return;
25
    }
26
27 6
    public function bySetMethod($data)
28
    {
29 6
        $data = $this->arrayIndexToCamelCase($data);
30 6
        $object = $this;
31 6
        $methods = get_class_methods($object);
32 6
        foreach ($methods as $method) {
33 6
            preg_match(' /^(set)(.*?)$/i', $method, $results);
34 6
            $setMethod = $results[1] ?? '';
35 6
            $attritbuteName = toCamelCase($results[2] ?? '');
36 6
            if ($setMethod == 'set' && !empty($data[$attritbuteName])) {
37 6
                $object->$method($this->getValue($data[$attritbuteName]));
38
            }
39
        }
40 6
        return $object;
41
    }
42
43
    /**
44
     * @param $data
45
     * @return array
46
     */
47 6
    protected function arrayIndexToCamelCase($data = [])
48
    {
49 6
        $newData = [];
50 6
        foreach ($data as $attribute => $value) {
51 6
            $attributeName = toCamelCase($attribute);
52 6
            $newData[$attributeName] = $value;
53
        }
54 6
        return $newData;
55
    }
56
57
    /**
58
     * @param $data
59
     */
60 18
    protected function byDinamicallyAttribute($data)
61
    {
62 18
        foreach ($data as $attribute => $value) {
63 18
            $attributeName = toCamelCase($attribute);
64 18
            $this->{$attributeName} = $this->getValue($value);
65
        }
66 18
    }
67
68
    /**
69
     * @param $value
70
     * @return mixed
71
     */
72 18
    protected function getValue($value)
73
    {
74 18
        if (!is_array($value) || !is_object_array($value)) {
75 18
            return $value;
76
        }
77 18
        return Response::resource($value);
78
    }
79
80
    /**
81
     * @return array
82
     */
83 3
    public function toArray(): array
84
    {
85 3
        return get_object_vars($this);
86
    }
87
}
88