1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Koine\Repository; |
4
|
|
|
|
5
|
|
|
use Koine\Repository\Entity\GeneratedIdInterface; |
6
|
|
|
|
7
|
|
|
class IdAwareRepository extends Repository |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* {@inheritdoc} |
11
|
|
|
* |
12
|
|
|
* @param GeneratedIdInterface $entity |
13
|
|
|
* |
14
|
|
|
* @return mixed |
15
|
|
|
*/ |
16
|
|
|
public function persist($entity) |
17
|
|
|
{ |
18
|
|
|
return $this->persistEntity($entity); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* {@inheritdoc} |
23
|
|
|
* |
24
|
|
|
* @param GeneratedIdInterface $entity |
25
|
|
|
* |
26
|
|
|
* @return mixed |
27
|
|
|
*/ |
28
|
|
|
protected function persistEntity(GeneratedIdInterface $entity) |
29
|
|
|
{ |
30
|
|
|
if ($entity->getId()) { |
31
|
|
|
return $this->update($entity); |
32
|
|
|
} else { |
33
|
|
|
return $this->insert($entity); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
* |
40
|
|
|
* @param GeneratedIdInterface $entity |
41
|
|
|
* |
42
|
|
|
* @return mixed |
43
|
|
|
*/ |
44
|
|
|
public function remove($entity) |
45
|
|
|
{ |
46
|
|
|
return $this->removeEntity($entity); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param GeneratedIdInterface $entity |
51
|
|
|
* |
52
|
|
|
* @return int |
53
|
|
|
*/ |
54
|
|
|
protected function insert(GeneratedIdInterface $entity) |
55
|
|
|
{ |
56
|
|
|
$data = $this->getHydrator()->extract($entity); |
57
|
|
|
$generatedId = $this->getStorage()->insert($data); |
58
|
|
|
|
59
|
|
|
if ($generatedId) { |
60
|
|
|
$entity->setGeneratedId($generatedId); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $generatedId; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param GeneratedIdInterface $entity |
68
|
|
|
* |
69
|
|
|
* @return mixed |
70
|
|
|
*/ |
71
|
|
|
protected function update(GeneratedIdInterface $entity) |
72
|
|
|
{ |
73
|
|
|
$data = $this->getHydrator()->extract($entity); |
74
|
|
|
|
75
|
|
|
$conditions = array( |
76
|
|
|
$this->getIdField() => $entity->getId(), |
77
|
|
|
); |
78
|
|
|
|
79
|
|
|
return $this->getStorage()->updateWhere($conditions, $data); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param GeneratedIdInterface $entity |
84
|
|
|
* |
85
|
|
|
* @return mixed |
86
|
|
|
*/ |
87
|
|
|
private function removeEntity(GeneratedIdInterface $entity) |
88
|
|
|
{ |
89
|
|
|
$conditions = array( |
90
|
|
|
$this->getIdField() => $entity->getId(), |
91
|
|
|
); |
92
|
|
|
|
93
|
|
|
$result = $this->getStorage()->deleteWhere($conditions); |
94
|
|
|
$entity->setGeneratedId(null); |
95
|
|
|
|
96
|
|
|
return $result; |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
/** |
100
|
|
|
* @return string |
101
|
|
|
*/ |
102
|
|
|
protected function getIdField() |
103
|
|
|
{ |
104
|
|
|
return 'id'; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|