auditionadmin/app/Actions/Schools/AssignUserToSchool.php

47 lines
1.4 KiB
PHP

<?php
namespace App\Actions\Schools;
use App\Exceptions\AuditionAdminException;
use App\Models\School;
use App\Models\User;
class AssignUserToSchool
{
public function __invoke(User $user, School $school): void
{
$this->assign($user, $school);
}
public function assign(User $user, School $school, bool $addDomainToSchool = true): void
{
if (! User::where('id', $user->id)->exists()) {
throw new AuditionAdminException('User does not exist');
}
if (! School::where('id', $school->id)->exists()) {
throw new AuditionAdminException('School does not exist');
}
// Save the old school for logging
$oldSchool = $user->school;
$affected = [];
// Set the new school
$user->school_id = $school->id;
$user->save();
if ($oldSchool) {
$message = 'Moved '.$user->full_name().' from school '.$oldSchool->name.' to school '.$school->name;
$affected = ['users' => [$user->id], 'schools' => [$oldSchool->id, $school->id]];
} else {
$message = 'Assigned '.$user->full_name().' to school '.$school->name;
$affected = ['users' => [$user->id], 'schools' => [$school->id]];
}
auditionLog($message, $affected);
$domainRecorder = app(AddSchoolEmailDomain::class);
if ($addDomainToSchool) {
$domainRecorder($school, $user->emailDomain());
}
}
}