name); $email = new EmailAddress($data->email); $endsOn = EmploymentEndDate::parse($data->employmentEndsOn); $this->transactions->run(function () use ($userId, $data, $name, $email, $endsOn): void { $user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId); $wasActiveAdmin = $user->isActiveAdmin(); if ($this->users->isEmailTaken($email, $userId)) { throw new EmailAlreadyInUse; } $user->changeDetails($name, $email, $data->role, $data->active, $endsOn, $data->supervisorId); if ($wasActiveAdmin && ! $user->isActiveAdmin() && $this->users->countActiveAdmins($userId) === 0) { throw new LastAdminCannotBeRemoved; } $this->supervisorRule->ensureValidFor($user); $this->users->save($user); }); } }