@@ -0,0 +1,95 @@
|
||||
<?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,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user