Completed
Push — master ( 8a83ac...f28038 )
by Gabriel
04:28
created

HasAttributesRecordTrait::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Nip\Records\Traits\HasAttributes;
4
5
use Nip\Utility\Str;
6
7
/**
8
 * Trait HasAttributesRecordTrait
9
 * @package Nip\Records\Traits\HasAttributes
10
 */
11
trait HasAttributesRecordTrait
12
{
13
    protected $_data;
14
15
    /**
16
     * @param $name
17
     * @return mixed
18
     */
19 21
    public function &__get($name)
20
    {
21 21
        if (!$this->__isset($name)) {
22 7
            $this->_data[$name] = null;
23
        }
24
25 21
        return $this->_data[$name];
26
    }
27
28
    /**
29
     * @param $name
30
     * @param $value
31
     */
32 19
    public function __set($name, $value)
33
    {
34 19
        $this->setAttribute($name, $value);
35 19
    }
36
37
    /**
38
     * @param $name
39
     * @return bool
40
     */
41 21
    public function __isset($name)
42
    {
43 21
        return isset($this->_data[$name]);
44
    }
45
46
    /**
47
     * @param $name
48
     */
49
    public function __unset($name)
50
    {
51
        unset($this->_data[$name]);
52
    }
53
54
    /**
55
     * @param $key
56
     * @param $value
57
     */
58 19
    public function setAttribute($key, $value)
59
    {
60 19
        if (property_exists($this, $key)) {
61
            $this->{$key} = $value;
62
            return;
63
        }
64
65 19
        $method = 'set' . Str::studly($key);
66 19
        if (method_exists($this, $method)) {
67
            $this->$method($value);
68
            return;
69
        }
70 19
        $method .= 'Attribute';
71 19
        if (method_exists($this, $method)) {
72
            $this->$method($value);
73
            return;
74
        }
75 19
        $this->setDataValue($key, $value);
76 19
    }
77
78
    /**
79
     * @param bool|array $data
80
     */
81 4
    public function writeData($data = false)
82
    {
83 4
        foreach ($data as $key => $value) {
84 4
            $this->__set($key, $value);
85
        }
86 4
    }
87
88
    /**
89
     * @param $key
90
     * @param $value
91
     */
92 19
    protected function setDataValue($key, $value)
93
    {
94 19
        $this->_data[$key] = $value;
95 19
    }
96
}
97