|
5 | 5 | namespace App\Model\Repository;
|
6 | 6 |
|
7 | 7 | use Dibi\Connection;
|
| 8 | +use Dibi\Row; |
| 9 | +use ReflectionClass; |
8 | 10 |
|
| 11 | +/** |
| 12 | + * @template T of Row |
| 13 | + */ |
9 | 14 | abstract class BaseRepository
|
10 | 15 | {
|
| 16 | + protected string $tableName; |
| 17 | + |
11 | 18 | public function __construct(
|
12 | 19 | protected Connection $dibi
|
13 | 20 | ) {
|
| 21 | + $reflect = new ReflectionClass($this); |
| 22 | + $repositoryName = str_replace('Repository', '', $reflect->getShortName()); |
| 23 | + |
| 24 | + $this->tableName = strtolower($repositoryName); |
14 | 25 | }
|
| 26 | + |
| 27 | + /** |
| 28 | + * @return T |
| 29 | + */ |
| 30 | + public function find(mixed $id): Row|null |
| 31 | + { |
| 32 | + $result = $this->dibi->query(" |
| 33 | + SELECT * FROM {$this->tableName} WHERE id=? |
| 34 | + ", |
| 35 | + $id |
| 36 | + ); |
| 37 | + |
| 38 | + return $result->fetch(); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * @return T |
| 43 | + */ |
| 44 | + public function findOneBy(array $criteria, array|null $orderBy = null): Row|null |
| 45 | + { |
| 46 | + $query = "SELECT * FROM {$this->tableName} WHERE %and"; |
| 47 | + |
| 48 | + if ($orderBy) { |
| 49 | + $query = $query . " ORDER BY %by"; |
| 50 | + } |
| 51 | + |
| 52 | + $arguments = [ |
| 53 | + $query, |
| 54 | + $criteria |
| 55 | + ]; |
| 56 | + |
| 57 | + if ($orderBy) { |
| 58 | + $arguments[] = $orderBy; |
| 59 | + } |
| 60 | + |
| 61 | + $result = $this->dibi->query(...$arguments); |
| 62 | + |
| 63 | + return $result->fetch(); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * @return array<array-key, T> |
| 68 | + */ |
| 69 | + public function findAll(): array |
| 70 | + { |
| 71 | + $result = $this->dibi->query(" |
| 72 | + SELECT * FROM {$this->tableName} |
| 73 | + "); |
| 74 | + |
| 75 | + return $result->fetchAll(); |
| 76 | + } |
| 77 | + |
| 78 | + public function getAllCount(): int |
| 79 | + { |
| 80 | + $result = $this->dibi->query(" |
| 81 | + SELECT * FROM {$this->tableName} |
| 82 | + "); |
| 83 | + |
| 84 | + return $result->getRowCount(); |
| 85 | + } |
15 | 86 | }
|
0 commit comments