Files
alrahma_sunday_school/app/Services/SchoolYearContextService.php
T
root e06ccc9cc0
Tests / PHPUnit (push) Failing after 40s
ADD SCHOOL YEAR MANAGEMENT
2026-07-12 02:21:39 -04:00

96 lines
2.6 KiB
PHP

<?php
namespace App\Services;
use App\Models\SchoolYearModel;
use App\Support\SchoolYear\SchoolYearContext;
use CodeIgniter\HTTP\IncomingRequest;
use RuntimeException;
final class SchoolYearContextService
{
public function __construct(
private readonly SchoolYearModel $schoolYearModel,
) {
}
public function resolve(
IncomingRequest $request,
?int $routeSchoolYearId = null
): SchoolYearContext {
$requestedId = $routeSchoolYearId
?? $this->normalizeInt($request->getGet('school_year_id'));
$requestedName = trim((string) $request->getGet('school_year'));
if ($requestedId !== null && $requestedName !== '') {
$row = $this->schoolYearModel->find($requestedId);
if ($row === null || (string) ($row['name'] ?? '') !== $requestedName) {
throw new RuntimeException('Selected school-year parameters conflict.');
}
return $this->fromRow($row, true);
}
if ($requestedId !== null) {
$row = $this->schoolYearModel->find($requestedId);
if ($row === null) {
throw new RuntimeException('Selected school year was not found.');
}
return $this->fromRow($row, true);
}
if ($requestedName !== '') {
$row = $this->schoolYearModel
->where('name', $requestedName)
->first();
if ($row === null) {
throw new RuntimeException('Selected school year was not found.');
}
return $this->fromRow($row, true);
}
$sessionYearId = session('selected_school_year_id');
if (is_numeric($sessionYearId)) {
$row = $this->schoolYearModel->find((int) $sessionYearId);
if ($row !== null) {
return $this->fromRow($row, false);
}
}
$active = $this->schoolYearModel->active();
if ($active === null) {
throw new RuntimeException('No active school year is configured.');
}
return $this->fromRow($active, false);
}
private function normalizeInt(mixed $value): ?int
{
if ($value === null || $value === '' || ! ctype_digit((string) $value)) {
return null;
}
return (int) $value;
}
private function fromRow(array $row, bool $explicit): SchoolYearContext
{
return new SchoolYearContext(
id: (int) $row['id'],
yearName: (string) $row['name'],
status: (string) $row['status'],
explicitSelection: $explicit,
);
}
}