AbstractModel::jsonSerialize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PagaMasTarde\Model;
4
5
use Nayjest\StrCaseConverter\Str;
6
7
/**
8
 * Class AbstractModel
9
 * @package PagaMasTarde\Model
10
 */
11
abstract class AbstractModel
12
{
13
    /**
14
     * Card constructor.
15
     *
16
     * @param $nonStandardCard
17
     */
18
    public function __construct($nonStandardCard)
19
    {
20
        $this->fill($nonStandardCard);
21
    }
22
23
    /**
24
     * @param $nonStandardCard
25
     */
26
    public function fill($nonStandardCard)
27
    {
28
        $nonStandardCard = $this->getArray($nonStandardCard);
29
30
        foreach ($nonStandardCard as $key => $value) {
31
            $this->fillKeyValue($key, $value);
32
        }
33
    }
34
35
    /**
36
     * Encode protected properties
37
     *
38
     * @return array
39
     */
40
    public function jsonSerialize()
41
    {
42
        $object = array();
43
        foreach ($this as $key => $value) {
44
            $object[$key] = $value;
45
        }
46
47
        return $object;
48
    }
49
50
    /**
51
     * @param $nonStandardCard
52
     *
53
     * @return array | false
54
     */
55
    protected function getArray($nonStandardCard)
56
    {
57
        if ($nonStandardCard instanceof \stdClass) {
58
            return (array) $nonStandardCard;
59
        }
60
61
        return is_array($nonStandardCard) ? $nonStandardCard : false;
62
    }
63
64
    /**
65
     * @param $key
66
     * @param $value
67
     */
68
    protected function fillKeyValue($key, $value)
69
    {
70
        $key = lcfirst(Str::toCamelCase($key));
71
        if (property_exists($this, $key)) {
72
            if (method_exists($this, 'autoFill' . ucfirst($key))) {
73
                $this->{'autoFill' . ucfirst($key)}($value);
74
            } else {
75
                $this->{$key} = $value;
76
            }
77
        }
78
    }
79
}
80