main • app/controllers/CollaboratorController.php
<?php
class CollaboratorController
{
public function show(int $repoId): void
{
$uid = require_auth();
$db = db();
$repo = repo_get($db, $repoId);
if (!$repo || (int)$repo['owner_id'] !== $uid) { http_response_code(403); exit("403"); }
$st = $db->prepare("SELECT c.id, c.role, u.username, u.email, c.created_at
FROM repo_collaborators c
JOIN users u ON u.id = c.user_id
WHERE c.repo_id=?
ORDER BY c.id DESC");
$st->execute([$repoId]);
$collabs = $st->fetchAll();
$title = $repo['owner_username'] . "/" . $repo['name'] . " / Collaborators";
require __DIR__ . '/../views/repos/collaborators.php';
}
public function add(int $repoId): void
{
$uid = require_auth();
csrf_verify();
$db = db();
$repo = repo_get($db, $repoId);
if (!$repo || (int)$repo['owner_id'] !== $uid) { http_response_code(403); exit("403"); }
$username = trim($_POST['username'] ?? '');
$role = $_POST['role'] ?? 'read';
if (!in_array($role, ['read','write'], true)) $role = 'read';
$st = $db->prepare("SELECT id FROM users WHERE username=? LIMIT 1");
$st->execute([$username]);
$u = $st->fetch();
if (!$u) { flash_set('err','User not found'); redirect("/r/$repoId/collaborators"); }
try {
$st = $db->prepare("INSERT INTO repo_collaborators (repo_id,user_id,role,created_at) VALUES (?,?,?,?)");
$st->execute([$repoId, (int)$u['id'], $role, now()]);
flash_set('ok','Collaborator added');
} catch (Throwable $e) {
$st = $db->prepare("UPDATE repo_collaborators SET role=? WHERE repo_id=? AND user_id=?");
$st->execute([$role, $repoId, (int)$u['id']]);
flash_set('ok','Collaborator updated');
}
redirect("/r/$repoId/collaborators");
}
public function remove(int $repoId, int $collabId): void
{
$uid = require_auth();
csrf_verify();
$db = db();
$repo = repo_get($db, $repoId);
if (!$repo || (int)$repo['owner_id'] !== $uid) { http_response_code(403); exit("403"); }
$st = $db->prepare("DELETE FROM repo_collaborators WHERE id=? AND repo_id=?");
$st->execute([$collabId, $repoId]);
flash_set('ok','Collaborator removed');
redirect("/r/$repoId/collaborators");
}
}