Files
alrahma_sunday_school_api/app/Policies/ClassProgressReportPolicy.php
T
2026-04-23 00:04:35 -04:00

74 lines
1.9 KiB
PHP

<?php
namespace App\Policies;
use App\Models\ClassProgressReport;
use App\Models\Configuration;
use App\Models\TeacherClass;
use App\Models\User;
class ClassProgressReportPolicy
{
public function viewAny(User $user): bool
{
return $user !== null;
}
public function view(User $user, ClassProgressReport $report): bool
{
return $this->owns($user, $report) || $this->isAdmin($user);
}
public function create(User $user): bool
{
return $user !== null;
}
public function update(User $user, ClassProgressReport $report): bool
{
return $this->owns($user, $report) || $this->isAdmin($user);
}
public function delete(User $user, ClassProgressReport $report): bool
{
return $this->owns($user, $report) || $this->isAdmin($user);
}
private function owns(User $user, ClassProgressReport $report): bool
{
if ((int) $report->teacher_id === (int) $user->id) {
return true;
}
$schoolYear = (string) (Configuration::getConfig('school_year') ?? '');
if ($schoolYear === '') {
return false;
}
$semester = (string) (Configuration::getConfig('semester') ?? '');
foreach (TeacherClass::assignedForSectionTerm((int) $report->class_section_id, $semester, $schoolYear) as $row) {
if ((int) ($row['teacher_id'] ?? 0) === (int) $user->id) {
return true;
}
}
return false;
}
private function isAdmin(User $user): bool
{
$roles = $user->roles()
->pluck('roles.name')
->map(fn ($name) => strtolower((string) $name))
->toArray();
foreach (['administrator', 'admin', 'principal', 'vice_principal', 'vice-principal'] as $role) {
if (in_array($role, $roles, true)) {
return true;
}
}
return false;
}
}