/
Repository.php
434 lines (365 loc) · 11 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
namespace Anna\Repositories;
use Anna\Config;
use Anna\Databases\Model;
use Anna\Error;
use Anna\Exceptions\MalformedDateException;
use Anna\Exceptions\ModelPropertyException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\Tools\Pagination\Paginator;
/**
* -----------------------------------------------------------
* Repository
* -----------------------------------------------------------.
*
* Repositório padrão, fornecido pelo sistema para trabalhar com o adaptador original do Doctrine2 ORM cadastrado
* nas configurações
*
* @author Cristiano Gomes <cmgomes.es@gmail.com>
*
* @since 06, novembro 2015
*/
class Repository extends \Anna\Repositories\Abstracts\Repository
{
/**
* Quantidade de items por página.
*
* @var int
*/
public $per_page = 15;
/**
* Nome do modelo utilizado por este repositório.
*
* @var Model
*/
public $model;
/**
* Não é necessário esta declaração, é apenas para gerar autocomplete nas IDE's.
*
* @var EntityManager
*/
protected $manager;
/**
* Função que persiste os dados da entidade informada no banco de dados.
*
* @param mixed $model Qualquer entidade válida do Doctrine
*
* @throws \Exception
*
* @return bool
*/
public function save($model = null)
{
$model = $model ? $model : $this->model;
if ($model->id) {
return $this->edit();
}
$model->created_at = new \DateTime('now');
try {
$this->manager->persist($model);
$this->manager->flush($model);
$this->model = $model;
} catch (OptimisticLockException $oe) {
Error::logFile($oe->getMessage());
throw $oe;
} catch (\Exception $e) {
Error::logFile($e->getMessage());
throw $e;
}
return true;
}
/**
* Remove o registro no banco de dados referente ao nome do modelo recebido como parâmetro
* Caso as opções de soft delete estejam configuradas o campo buscará por a data atual no campo informado
* como delflag nas configurações do aplicativo.
*
* @param int $id valor da chave primária do registro
*
* @return false|null
*/
public function remove($id)
{
$modelname = get_class($this->model);
$metadata = $this->manager->getClassMetadata($modelname);
$table_name = $metadata->getTableName();
$primary_key = $metadata->getSingleIdentifierFieldName();
$this->model = $this->search([$primary_key => $id], true);
if (!$this->model instanceof Model) {
Error::log(new \Exception('Não foi encontrado registro na tabela: '.$table_name));
return false;
}
if (Config::getInstance()->get('database.softdelete')) {
$delflag = Config::getInstance()->get('database.delflag');
$bin_field = $delflag;
$this->model->$bin_field = new \Datetime('now');
try {
$this->manager->merge($this->model);
$this->manager->flush();
} catch (\Exception $e) {
Error::log($e);
return false;
}
} else {
try {
$this->manager->remove($this->model);
$this->manager->flush();
} catch (\Exception $e) {
Error::log($e);
return false;
}
}
}
/**
* Função editar dados já persistidos no banco de dados.
*
* @param mixed $model Qualquer entidade válida do Doctrine
*
* @return bool
*/
public function edit($model = null)
{
$model = $model ? $model : $this->model;
try {
$this->manager->merge($model);
$this->manager->flush();
} catch (\Exception $e) {
Error::log($e);
return false;
}
return true;
}
/**
* Função para buscas simples no banco de dados, para buscas mais complexas
* utilizar o QueryBuilder do Doctrine.
*
* @param array $filters formato do array: ['campo_da_tabela' => 'valor para filtro']
* @param bool $one true retorna apenas 1 registro
*
* @return mixed Instância do Model se os dados foram encontrados e on estiver setado, neste caso a propriedade model
* deste repositório irá ser atualizada com os dados encontrados.
*
* Array se one for false (padrão), neste caso retorna um collecion com as entidades
* encontradas.
*
* False se houver algum erro
*/
public function search($filters, $one = false)
{
$modelname = get_class($this->model);
try {
if ($one) {
$this->model = $this->manager->getRepository($modelname)->findOneBy($filters);
return $this->model;
} else {
$entities = $this->manager->getRepository($modelname)->findBy($filters);
return $entities;
}
} catch (\Exception $e) {
Error::log($e);
return false;
}
}
/**
* Efetua a persistencia dos dados em banco.
*
* @param Model $model
*
* @return bool
*/
public function persist(Model $model)
{
try {
$this->manager->persist($model);
} catch (\Exception $e) {
Error::log($e);
return false;
}
return true;
}
/**
* Efetua o merge do model atual com o banco de dados persistindo os dados editados.
*
* @param Model $model
*/
public function merge(Model $model)
{
try {
$this->manager->merge($model);
} catch (\Exception $e) {
Error::log($e);
return false;
}
return true;
}
public function find($id)
{
$model = $this->manager->find(get_class($this->model), $id);
if ($model) {
$this->model = $model;
}
return $model;
}
/**
* Comita as alterações/inserções para o banco de dados.
*
* Por padrão o Doctrine2 não comita
*
* @return bool
*/
public function flush()
{
try {
$this->manager->flush();
} catch (\Exception $e) {
$this->manager->rollback();
Error::log($e);
return false;
}
return true;
}
/**
* Entrega a ferramenta QueryBuider do Doctrine2 para construção de queries customizadas utilizando DQL.
*
* @return \Doctrine\ORM\QueryBuilder
*/
public function createQueryBuilder()
{
return $this->manager->createQueryBuilder();
}
/**
* Retorna um objeto PDO para uso de SQL's manuais.
*
* @return \Doctrine\DBAL\Driver\Connection
*/
public function getPdo()
{
return $this->manager->getConnection()->getWrappedConnection();
}
/**
* Busca registros nos parametros POST de entrada com o mesmo nome das propriedades do modelo registrado e
* preenche automaticamente seus valores.
*
* @throws MalformedDateException
*
* @return Model
*/
public function autoFill(array $params, string $modelClass = null)
{
if (!empty($modelClass)) {
$this->model = new $modelClass();
$this->model->created_at = new \DateTime('now');
}
$fields = $this->manager->getClassMetadata(get_class($this->model))->getFieldNames();
foreach ($fields as $field) {
if (!isset($params[$field])) {
continue;
}
if (strstr($field, 'date')) {
$dt = \DateTime::createFromFormat('Y-m-d H:i:s', $params[$field]);
if ($dt !== false && !array_sum($dt->getLastErrors())) {
$this->model->$field = $dt;
continue;
}
$dt = \DateTime::createFromFormat('Y-m-d', $params[$field]);
if ($dt !== false && !array_sum($dt->getLastErrors())) {
$this->model->$field = $dt;
continue;
}
throw new MalformedDateException("O valor do campo {$field}, é uma data inválida.");
}
$this->model->$field = $params[$field];
}
return $this->model;
}
/**
* Seta um valor na propriedade informada do model, caso contrário lança excessão.
*
* @throws ModelPropertyException
*/
public function setValue($field, $value)
{
$modelName = get_class($this->model);
$fields = $this->manager->getClassMetadata($modelName)
->getFieldNames();
if (!in_array($field, $fields)) {
throw new ModelPropertyException("O campo {$field} não existe no modelo {$modelName}.");
}
$this->model->$field = $value;
}
/**
* registra o model específico para persistência.
*
* @param Model $model
*
* @return Repository
*/
public function setModel(Model $model)
{
$this->model = $model;
return $this;
}
/**
* Inicia transação no banco de dados.
*/
public function begin()
{
$this->manager->beginTransaction();
}
/**
* Reverte alterações de uma transação.
*/
public function rollback()
{
$this->manager->rollback();
}
/**
* Commita as alterações realizadas na transação.
*/
public function commit()
{
$this->manager->commit();
}
/**
* Paginador padrão, efetua a busca com base nos filtros recebidos e retorna componente de paginação.
*
* @param int $page
* @param array $filters
*
* @return Paginator
*/
public function paginate($page = 1, $filters = null)
{
$offset = ($page == 1) ? 0 : $page * $this->per_page;
$qb = $this->manager->createQueryBuilder();
$qb->select('a')->from(get_class($this->model), 'a');
if (is_array($filters)) {
foreach ($filters as $field => $value) {
if ($value !== null) {
$qb->where("a.$field = :$field")->setParameter($field, $value);
} else {
$qb->where("a.$field IS NULL");
}
}
}
$query = $qb->getQuery();
unset($qb);
$query->setFirstResult($offset);
$query->setMaxResults($this->per_page);
try {
$paginator = new Paginator($query);
} catch (\Exception $e) {
Error::log($e);
return false;
}
$paginator = new \Anna\Paginator($paginator, $this->per_page, $page);
return $paginator;
}
/**
* @return EntityManager
*/
public function getEntityManager()
{
return $this->manager;
}
}