1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HnrAzevedo\Datamanager; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
|
7
|
|
|
trait EntityTrait{ |
8
|
|
|
public function toEntity() |
9
|
|
|
{ |
10
|
|
|
if($this->getCount() === 0){ |
|
|
|
|
11
|
|
|
return null; |
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
$entity = $this->setByDatabase($this->result[0]); |
|
|
|
|
15
|
|
|
|
16
|
|
|
if(count($this->result) > 1){ |
17
|
|
|
$entity = []; |
18
|
|
|
foreach ($this->result as $key => $value) { |
19
|
|
|
$entity[] = $this->setByDatabase($value); |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
return $entity; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function persist() |
27
|
|
|
{ |
28
|
|
|
$columns = ''; |
29
|
|
|
$values = ''; |
30
|
|
|
$data = []; |
31
|
|
|
|
32
|
|
|
foreach ($this->data as $key => $value) { |
33
|
|
|
if(strstr($this->data[$key]['extra'],'auto_increment')){ |
34
|
|
|
continue; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$this->checkMaxlength($key, $value['value'], $value['maxlength']); |
|
|
|
|
38
|
|
|
|
39
|
|
|
$columns .= $key.','; |
40
|
|
|
$values .= ':'.$key.','; |
41
|
|
|
$data[$key] = $value['value']; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$this->transaction('begin'); |
|
|
|
|
45
|
|
|
try{ |
46
|
|
|
|
47
|
|
|
$id = $this->insert($data); |
|
|
|
|
48
|
|
|
|
49
|
|
|
$this->check_fail(); |
|
|
|
|
50
|
|
|
|
51
|
|
|
$this->getData()[$this->primary]['value'] = $id; |
|
|
|
|
52
|
|
|
|
53
|
|
|
$this->transaction('commit'); |
54
|
|
|
|
55
|
|
|
}catch(Exception $er){ |
56
|
|
|
$this->transaction('rollback'); |
57
|
|
|
throw $er; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $this; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function remove(?bool $exec = false) |
64
|
|
|
{ |
65
|
|
|
if($exec !== null){ |
66
|
|
|
$this->clause = 'remove'; |
|
|
|
|
67
|
|
|
return $this; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$this->clause = null; |
71
|
|
|
|
72
|
|
|
if(count($this->where) == 1){ |
73
|
|
|
$this->removeById(); |
|
|
|
|
74
|
|
|
return $this; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$this->delete($this->mountRemove()['where'], substr( $this->mountRemove()['data'] ,0,-1) ); |
|
|
|
|
78
|
|
|
|
79
|
|
|
$this->check_fail(); |
80
|
|
|
|
81
|
|
|
return $this; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
public function save() |
85
|
|
|
{ |
86
|
|
|
$this->transaction('begin'); |
87
|
|
|
|
88
|
|
|
try{ |
89
|
|
|
$this->update( |
|
|
|
|
90
|
|
|
$this->mountSave()['data'], |
|
|
|
|
91
|
|
|
"{$this->primary}=:{$this->primary}", |
92
|
|
|
$this->primary.'='.$this->getData()[$this->primary]['value'] |
93
|
|
|
); |
94
|
|
|
|
95
|
|
|
$this->check_fail(); |
96
|
|
|
|
97
|
|
|
$this->transaction('commit'); |
98
|
|
|
}catch(Exception $er){ |
99
|
|
|
$this->transaction('rollback'); |
100
|
|
|
throw $er; |
101
|
|
|
} |
102
|
|
|
|
103
|
|
|
return $this; |
104
|
|
|
} |
105
|
|
|
} |