/
Repository.php
321 lines (245 loc) · 7.46 KB
/
Repository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<?php
/**
* This file is part of the YetORM package
*
* @license MIT
* @author Petr Kessler (https://kesspess.cz)
* @link https://github.com/uestla/YetORM
*/
namespace YetORM;
use Nette;
use Nette\Database\IRow as NIRow;
use Nette\Reflection\AnnotationsParser;
use YetORM\Reflection\AnnotationProperty;
use Nette\Database\Context as NdbContext;
use YetORM\Exception\InvalidArgumentException;
use Nette\Database\Table\ActiveRow as NActiveRow;
use Nette\Database\Table\Selection as NSelection;
abstract class Repository
{
use Nette\SmartObject {
__call as public netteCall;
}
/** @var NdbContext */
protected $database;
/** @var Transaction */
private $transaction;
/** @var string|NULL */
protected $table = NULL;
/** @var string|NULL */
protected $entity = NULL;
/** @param NdbContext $database */
public function __construct(NdbContext $database)
{
$this->database = $database;
$this->transaction = new Transaction($database->getConnection());
}
/**
* @param NActiveRow|Record $row
* @return Entity
*/
public function createEntity($row = NULL)
{
$class = $this->getEntityClass();
return new $class($row);
}
/**
* @param mixed $id
* @return Entity|NULL
*/
public function getByID($id)
{
$selection = $this->getTable()->wherePrimary($id);
return $this->createEntityFromSelection($selection);
}
/**
* @param array $criteria
* @return Entity|NULL
*/
public function getBy(array $criteria)
{
$selection = $this->getTable()->where($criteria);
return $this->createEntityFromSelection($selection);
}
/**
* @param array $criteria
* @return EntityCollection
*/
public function findBy(array $criteria)
{
$selection = $this->getTable()->where($criteria);
return $this->createCollection($selection);
}
/** @return EntityCollection */
public function findAll()
{
return $this->findBy([]);
}
/**
* @param NSelection $selection
* @return Entity|NULL
*/
protected function createEntityFromSelection(NSelection $selection)
{
$row = $selection->fetch();
return $row === FALSE ? NULL : $this->createEntity($row);
}
/**
* @param NSelection $selection
* @param string|callable $entity
* @param string $refTable
* @param string $refColumn
* @return EntityCollection
*/
protected function createCollection($selection, $entity = NULL, $refTable = NULL, $refColumn = NULL)
{
return new EntityCollection($selection, $entity === NULL ? [$this, 'createEntity'] : $entity, $refTable, $refColumn);
}
/**
* @param Entity $entity
* @return bool
*/
public function persist(Entity $entity)
{
$this->checkEntity($entity);
return $this->transaction(function () use ($entity) {
$record = $entity->toRecord();
if ($record->hasRow()) {
return $record->update();
}
$inserted = $this->getTable()
->insert($record->getModified());
if (!$inserted instanceof NIRow) {
throw new Exception\InvalidStateException('Insert did not return instance of ' . NIRow::class . '. '
. 'Does table "' . $this->getTableName() . '" have primary key defined? If so, try cleaning cache.');
}
$record->setRow($inserted);
return TRUE;
});
}
/**
* @param Entity $entity
* @return bool
*/
public function delete(Entity $entity)
{
$this->checkEntity($entity);
$record = $entity->toRecord();
if ($record->hasRow()) {
return $this->transaction(function () use ($record) {
return $record->getRow()->delete() > 0;
});
}
return TRUE;
}
/**
* @param string $table
* @return NSelection
*/
protected function getTable($table = NULL)
{
return $this->database->table($table === NULL ? $this->getTableName() : $table);
}
/** @return string */
final protected function getTableName()
{
if ($this->table === NULL) {
$ref = Nette\Reflection\ClassType::from($this);
if (($annotation = $ref->getAnnotation('table')) === NULL) {
throw new Exception\InvalidStateException('Table name not set. Use either annotation @table or class member ' . $ref->getName() . '::$table');
}
$this->table = $annotation;
}
return $this->table;
}
/** @return string */
final protected function getEntityClass()
{
if ($this->entity === NULL) {
$ref = Nette\Reflection\ClassType::from($this);
if (($annotation = $ref->getAnnotation('entity')) === NULL) {
throw new Exception\InvalidStateException('Entity class not set. Use either annotation @entity or class member ' . $ref->getName() . '::$entity');
}
$this->entity = AnnotationsParser::expandClassName($annotation, $ref);
}
return $this->entity;
}
/** @return void */
final protected function checkEntity(Entity $entity)
{
$class = $this->getEntityClass();
if (!$entity instanceof $class) {
throw new Exception\InvalidArgumentException("Instance of '$class' expected, '"
. get_class($entity) . "' given.");
}
}
/**
* @param string $name
* @param array $args
* @return mixed
*/
public function __call($name, $args)
{
if (strncmp($name, 'getBy', 5) === 0) {
$selection = $this->getTable()->limit(1);
$properties = explode('And', substr($name, 5));
if (count($properties) !== count($args)) {
throw new Exception\InvalidArgumentException('Wrong number of argument passed to ' . $name . ' method - ' . count($properties) . ' expected, ' . count($args) . ' given.');
}
$ref = Reflection\EntityType::from($class = $this->getEntityClass());
foreach ($properties as $key => $property) {
$property = lcfirst($property);
$prop = $ref->getEntityProperty($property);
if ($prop === NULL) {
throw new Exception\InvalidArgumentException("Property '\$$property' not found in entity '$class'.");
}
if (!$prop instanceof AnnotationProperty) {
throw new InvalidArgumentException("Cannot use " . static::getReflection()->getName() . "::$name() - missing @property definition of $class::\$$property.");
}
$selection->where($prop->getColumn(), $args[$key]);
}
return $this->createEntityFromSelection($selection);
} elseif (strncmp($name, 'findBy', 6) === 0) {
$properties = explode('And', substr($name, 6));
if (count($properties) !== count($args)) {
throw new Exception\InvalidArgumentException('Wrong number of argument passed to ' . $name . ' method - ' . count($properties) . ' expected, ' . count($args) . ' given.');
}
$criteria = [];
$ref = Reflection\EntityType::from($class = $this->getEntityClass());
foreach ($properties as $key => $property) {
$property = lcfirst($property);
$prop = $ref->getEntityProperty($property);
if ($prop === NULL) {
throw new Exception\InvalidArgumentException("Missing @property definition of $class::\$$property.");
}
if (!$prop instanceof AnnotationProperty) {
$refs = Nette\Reflection\ClassType::from($this);
throw new InvalidArgumentException("Cannot use " . $refs->getName() . "::$name() - missing @property definition of $class::\$$property.");
}
$criteria[$prop->getColumn()] = $args[$key];
}
return $this->findBy($criteria);
}
return $this->netteCall($name, $args);
}
// === TRANSACTION HELPERS ====================================================
/**
* @param \Closure $callback
* @return mixed
*/
final protected function transaction(\Closure $callback)
{
try {
return $this->transaction->transaction($callback);
} catch (\Exception $e) {
$this->handleException($e);
throw $e;
}
}
/**
* @param \Exception $e
* @return void
*/
protected function handleException(\Exception $e)
{}
}