|
- <?php
-
- declare(strict_types=1);
-
- namespace App\Repositories;
-
- use App\Models\Board;
- use Core\Repository;
-
- class BoardRepository extends Repository
- {
- protected string $table = 'boards';
-
- public function findBySlug(string $slug): ?Board
- {
- $row = $this->database->first(
- 'SELECT * FROM boards WHERE slug = :slug',
- ['slug' => $slug]
- );
-
- return $row ? Board::fromRow($row) : null;
- }
-
- /** @return Board[] */
- public function getAll(): array
- {
- $rows = $this->database->query('SELECT * FROM boards ORDER BY name ASC');
-
- return array_map(fn(array $r) => Board::fromRow($r), $rows);
- }
-
- public function slugExists(string $slug, int $excludeId = 0): bool
- {
- if ($excludeId > 0) {
- $row = $this->database->first(
- 'SELECT COUNT(*) AS cnt FROM boards WHERE slug = :slug AND id != :id',
- ['slug' => $slug, 'id' => $excludeId]
- );
- } else {
- $row = $this->database->first(
- 'SELECT COUNT(*) AS cnt FROM boards WHERE slug = :slug',
- ['slug' => $slug]
- );
- }
-
- return (int) ($row['cnt'] ?? 0) > 0;
- }
-
- public function uniqueSlug(string $base, int $excludeId = 0): string
- {
- $candidate = $base;
- $suffix = 2;
-
- while ($this->slugExists($candidate, $excludeId)) {
- $candidate = $base . '-' . $suffix;
- $suffix++;
- }
-
- return $candidate;
- }
-
- public function insert(Board $board): Board
- {
- $this->database->execute(
- 'INSERT INTO boards
- (name, slug, import_from_printstream, printstream_job_name, created_at, created_by, updated_at, updated_by)
- VALUES
- (:name, :slug, :import_from_printstream, :printstream_job_name, :created_at, :created_by, :updated_at, :updated_by)',
- [
- 'name' => $board->name,
- 'slug' => $board->slug,
- 'import_from_printstream' => $board->importFromPrintstream ? 1 : 0,
- 'printstream_job_name' => $board->printstreamJobName,
- 'created_at' => $board->createdAt,
- 'created_by' => $board->createdBy,
- 'updated_at' => $board->updatedAt,
- 'updated_by' => $board->updatedBy,
- ]
- );
-
- $row = $this->database->first('SELECT last_insert_rowid() AS id');
- $board->id = (int) ($row['id'] ?? 0);
-
- return $board;
- }
-
- public function update(Board $board): void
- {
- $this->database->execute(
- 'UPDATE boards
- SET name = :name, slug = :slug, import_from_printstream = :import_from_printstream,
- printstream_job_name = :printstream_job_name, updated_at = :updated_at, updated_by = :updated_by
- WHERE id = :id',
- [
- 'name' => $board->name,
- 'slug' => $board->slug,
- 'import_from_printstream' => $board->importFromPrintstream ? 1 : 0,
- 'printstream_job_name' => $board->printstreamJobName,
- 'updated_at' => $board->updatedAt,
- 'updated_by' => $board->updatedBy,
- 'id' => $board->id,
- ]
- );
- }
- }
|