Completed
Push — master ( 345c65...427685 )
by Alex Ribeiro de
04:48 queued 02:57
created

ResourceContract::toObject()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 3
rs 10
c 0
b 0
f 0
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 15
        $this->byDinamicallyAttribute($data);
24 15
        return;
25
    }
26
27
    /**
28
     * @param $data
29
     */
30 6
    protected function bySetMethod($data)
31
    {
32 6
        $setMethods = preg_grep("/^set/", get_class_methods($this));
33 6
        foreach ($setMethods as $method) {
34 6
            $this->{$method}($this->toObject($data));
35
        }
36 6
    }
37
38
39
    /**
40
     * @param $data
41
     */
42 15
    protected function byDinamicallyAttribute($data)
43
    {
44 15
        foreach ($data as $attribute => $value) {
45 15
            $attributeName = toCamelCase($attribute);
46 15
            $this->{$attributeName} = $this->getValue($value);
47
        }
48 15
    }
49
50
    /**
51
     * @param $data
52
     * @return ResourceContract
53
     */
54 6
    protected function toObject($data)
55
    {
56 6
        if (is_object($data)) {
57 3
            return $data;
58
        }
59
60 3
        $object = clone $this;
61 3
        foreach ($data as $attribute => $value) {
62 3
            $attributeName = toCamelCase($attribute);
63 3
            $object->{$attributeName} = $value;
64
        }
65 3
        return $object;
66
    }
67
68
69
    /**
70
     * @param $value
71
     * @return mixed
72
     */
73 15
    protected function getValue($value)
74
    {
75 15
        if (!is_array($value) || !is_object_array($value)) {
76 15
            return $value;
77
        }
78 15
        return Response::resource($value);
79
    }
80
81
    /**
82
     * @return array
83
     */
84 3
    public function toArray(): array
85
    {
86 3
        return get_object_vars($this);
87
    }
88
}
89