031e499819
API CI/CD / Validate (composer + pint) (push) Successful in 3m10s
API CI/CD / Test (PHPUnit) (push) Failing after 6m49s
API CI/CD / Build frontend assets (push) Successful in 1m3s
API CI/CD / Security audit (push) Failing after 1m0s
API CI/CD / Deploy to shared hosting (PHP) (push) Has been skipped
90 lines
2.6 KiB
PHP
90 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services\SchoolYears;
|
|
|
|
use App\Models\Configuration;
|
|
use App\Models\SchoolYear;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
|
|
|
class SelectedSchoolYearContextService
|
|
{
|
|
public function __construct(private SchoolYearResolver $resolver) {}
|
|
|
|
public function fromRequest(Request $request): SelectedSchoolYearContext
|
|
{
|
|
$explicit = false;
|
|
$name = $this->selectedName($request, $explicit);
|
|
|
|
if ($name === '') {
|
|
$name = $this->activeSchoolYearName();
|
|
}
|
|
|
|
if ($name === '') {
|
|
throw new UnprocessableEntityHttpException('A school_year value is required.');
|
|
}
|
|
|
|
if (! Schema::hasTable('school_years')) {
|
|
throw new UnprocessableEntityHttpException('School-year tracking is unavailable.');
|
|
}
|
|
|
|
$this->resolver->ensureCurrentTracked();
|
|
|
|
$year = SchoolYear::query()->where('name', $name)->first();
|
|
if (! $year) {
|
|
throw new NotFoundHttpException(sprintf('School year %s was not found.', $name));
|
|
}
|
|
|
|
return new SelectedSchoolYearContext(
|
|
(int) $year->id,
|
|
(string) $year->name,
|
|
(string) $year->status,
|
|
in_array($year->status, [SchoolYear::STATUS_CLOSED, SchoolYear::STATUS_ARCHIVED], true),
|
|
);
|
|
}
|
|
|
|
public function fromName(string $schoolYear): SelectedSchoolYearContext
|
|
{
|
|
$request = Request::create('/', 'GET', ['school_year' => $schoolYear]);
|
|
|
|
return $this->fromRequest($request);
|
|
}
|
|
|
|
private function selectedName(Request $request, bool &$explicit): string
|
|
{
|
|
$sources = [
|
|
$request->query('school_year'),
|
|
$request->headers->get('X-School-Year'),
|
|
$request->input('school_year'),
|
|
];
|
|
|
|
foreach ($sources as $value) {
|
|
if (is_string($value) && trim($value) !== '') {
|
|
$explicit = true;
|
|
|
|
return trim($value);
|
|
}
|
|
}
|
|
|
|
return '';
|
|
}
|
|
|
|
private function activeSchoolYearName(): string
|
|
{
|
|
$configured = trim((string) (Configuration::getConfig('school_year') ?? ''));
|
|
if ($configured !== '') {
|
|
return $configured;
|
|
}
|
|
|
|
if (! Schema::hasTable('school_years')) {
|
|
return '';
|
|
}
|
|
|
|
$year = SchoolYear::query()->where('is_current', true)->orderByDesc('id')->first();
|
|
|
|
return $year ? trim((string) $year->name) : '';
|
|
}
|
|
}
|