Completed
Push — master ( 09bb07...3577e6 )
by Gabriel
04:08 queued 10s
created

ActiveRecordTrait::update()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Nip\Records\Traits\ActiveRecord;
4
5
use Nip\Records\AbstractModels\Record;
6
use Nip\Records\Traits\AbstractTrait\RecordTrait;
7
use Nip\Records\Traits\HasPrimaryKey\RecordTrait as HasPrimaryKeyTrait;
8
9
/**
10
 * Class ActiveRecordTrait
11
 * @package Nip\Records\Traits\ActiveRecord
12
 */
13
trait ActiveRecordTrait
14
{
15
    use RecordTrait;
16
    use HasPrimaryKeyTrait;
17
18
    protected $dbData = [];
19
20
    /**
21
     * @param bool|array $data
22
     */
23 4
    public function writeDBData($data = false)
24
    {
25 4
        foreach ($data as $key => $value) {
26 1
            $this->dbData[$key] = $value;
27
        }
28 4
    }
29
30
    /**
31
     * @return array
32
     */
33
    public function getDBData()
34
    {
35
        return $this->dbData;
36
    }
37
38
    /**
39
     * @param $field
40
     * @return bool
41
     */
42 1
    public function fieldUpdatedFromDb($field)
43
    {
44 1
        if (!isset($this->{$field})) {
45 1
            return false;
46
        }
47 1
        if (!isset($this->dbData[$field])) {
48
            return false;
49
        }
50 1
        if ($this->{$field} == $this->dbData[$field]) {
51 1
            return false;
52
        }
53 1
        return true;
54
    }
55
56
    /**
57
     * @return bool
58
     */
59
    public function insert()
60
    {
61
        $pk = $this->getManager()->getPrimaryKey();
62
        $lastId = $this->getManager()->insert($this);
63
        if ($pk == 'id') {
64
            $this->{$pk} = $lastId;
65
        }
66
67
        return $lastId > 0;
68
    }
69
70
    /**
71
     * @return bool|\Nip\Database\Result
72
     */
73
    public function update()
74
    {
75
        $return = $this->getManager()->update($this);
76
        return $return;
77
    }
78
79
    public function save()
80
    {
81
        $this->getManager()->save($this);
82
    }
83
84
    public function saveRecord()
85
    {
86
        $this->getManager()->save($this);
87
    }
88
89
    public function delete()
90
    {
91
        $this->getManager()->delete($this);
92
    }
93
94
    /**
95
     * @return bool
96
     */
97
    public function isInDB()
98
    {
99
        $primaryKey = $this->getManager()->getPrimaryKey();
100
        return $this->{$primaryKey} > 0;
101
    }
102
103
    /**
104
     * @return bool|false|Record
105
     */
106
    public function exists()
107
    {
108
        return $this->getManager()->exists($this);
109
    }
110
}
111