refactor: code style changes

Signed-off-by: miguel456 <me@nogueira.codes>
This commit is contained in:
2023-01-15 00:04:00 +00:00
parent 25155bff2e
commit 3727c84f3e
146 changed files with 1013 additions and 1341 deletions

View File

@@ -15,29 +15,24 @@ use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Spatie\Permission\Models\Role;
class AbsenceService
{
/**
* Determines whether someone already has an active leave of absence request
*
* @param User $user The user to check
* @param User $user The user to check
* @return bool Their status
*/
public function hasActiveRequest(Authenticatable $user): bool {
public function hasActiveRequest(Authenticatable $user): bool
{
$absences = Absence::where('requesterID', $user->id)->get();
foreach ($absences as $absence) {
// Or we could adjust the query (using a model scope) to only return valid absences;
// If there are any, refuse to store more, but this approach also works
// A model scope that only returns cancelled, declined and ended absences could also be implemented for future use
if (in_array($absence->getRawOriginal('status'), ['PENDING', 'APPROVED']))
{
if (in_array($absence->getRawOriginal('status'), ['PENDING', 'APPROVED'])) {
return true;
}
}
@@ -47,12 +42,11 @@ class AbsenceService
public function createAbsence(Authenticatable $requester, Request $request)
{
$absence = Absence::create([
'requesterID' => $requester->id,
'start' => $request->start_date,
'predicted_end' => $request->predicted_end,
'available_assist' => $request->available_assist == "on",
'available_assist' => $request->available_assist == 'on',
'reason' => $request->reason,
'status' => 'PENDING',
]);
@@ -65,22 +59,21 @@ class AbsenceService
}
});
Log::info('Processing new leave of absence request.', [
'requesting_user' => $requester->email,
'absenceid' => $absence->id,
'reason' => $request->reason
'reason' => $request->reason,
]);
return $absence;
}
/**
* Sets an absence as Approved.
*
* @param Absence $absence The absence to approve.
* @param Absence $absence The absence to approve.
* @return Absence The approved absence.
*
* @throws AbsenceNotActionableException
*/
public function approveAbsence(Absence $absence)
@@ -88,19 +81,19 @@ class AbsenceService
Log::info('An absence request has just been approved.', [
'absenceid' => $absence->id,
'reviewing_admim' => Auth::user()->email,
'new_status' => 'APPROVED'
'new_status' => 'APPROVED',
]);
$absence->setApproved()
->requester->notify(new AbsenceRequestApproved($absence));
}
/**
* Sets an absence as Declined.
*
* @param Absence $absence The absence to decline.
* @param Absence $absence The absence to decline.
* @return Absence The declined absence.
*
* @throws AbsenceNotActionableException
*/
public function declineAbsence(Absence $absence)
@@ -108,26 +101,26 @@ class AbsenceService
Log::warning('An absence request has just been declined.', [
'absenceid' => $absence->id,
'reviewing_admim' => Auth::user()->email,
'new_status' => 'DECLINED'
'new_status' => 'DECLINED',
]);
$absence->setDeclined()
->requester->notify(new AbsenceRequestDeclined($absence));
}
/**
* Sets an absence as Cancelled.
*
* @param Absence $absence The absence to cancel.
* @param Absence $absence The absence to cancel.
* @return Absence The cancelled absence.
*
* @throws AbsenceNotActionableException
*/
public function cancelAbsence(Absence $absence)
{
Log::warning('An absence request has just been cancelled (only cancellable by requester).', [
'absenceid' => $absence->id,
'new_status' => 'CANCELLED'
'new_status' => 'CANCELLED',
]);
$absence->setCancelled()
@@ -137,14 +130,14 @@ class AbsenceService
/**
* Sets an absence as Ended.
*
* @param Absence $absence
* @param Absence $absence
* @return bool
*/
public function endAbsence(Absence $absence)
{
Log::info('An absence request has just expired.', [
'absenceid' => $absence->id,
'new_status' => 'ENDED'
'new_status' => 'ENDED',
]);
$absence->setEnded()
@@ -154,7 +147,7 @@ class AbsenceService
/**
* Removes an absence
*
* @param Absence $absence The absence to remove.
* @param Absence $absence The absence to remove.
* @return bool Whether the absence was removed.
*/
public function removeAbsence(Absence $absence): bool
@@ -169,20 +162,16 @@ class AbsenceService
/**
* End all expired absences in the application
*
* @return void
*/
public function endExpired(): void
{
foreach (Absence::all() as $absence)
{
foreach (Absence::all() as $absence) {
// tell the absence we want to check for cancelability
if (!Carbon::parse($absence->predicted_end)->isFuture() && $absence->isActionable(true)) {
if (! Carbon::parse($absence->predicted_end)->isFuture() && $absence->isActionable(true)) {
$this->endAbsence($absence);
}
}
}
}

View File

@@ -1,5 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace App\Services;
@@ -13,22 +14,21 @@ use Illuminate\Support\Facades\Log;
class AccountSuspensionService
{
/**
* Suspends a user account, with given $reason.
* Permanent if no duration given.
*
* @param User $target Who to suspend.
* @param string $reason Suspension reason.
* @param int|null $duration Duration in days
* @param User $target Who to suspend.
* @param string $reason Suspension reason.
* @param int|null $duration Duration in days
* @return Ban The ban itself
*/
public function suspend(User $target, string $reason, int $duration = null): Ban {
Log::alert("An user account has just been suspended.", [
public function suspend(User $target, string $reason, int $duration = null): Ban
{
Log::alert('An user account has just been suspended.', [
'taget_email' => $target->email,
'suspended_by' => Auth::user()->email,
'reason' => $reason
'reason' => $reason,
]);
if ($duration > 0) {
@@ -40,18 +40,18 @@ class AccountSuspensionService
'reason' => $reason,
'bannedUntil' => ($duration > 0) ? $expiryDate->format('Y-m-d H:i:s') : null,
'authorUserID' => Auth::user()->id,
'isPermanent' => ($duration == 0) ? true : false
'isPermanent' => ($duration == 0) ? true : false,
]);
}
/**
* Lifts someone's suspension
*
* @param User $user The user to unsuspend
* @param User $user The user to unsuspend
*/
public function unsuspend(User $user): void {
Log::alert("A suspension has just been lifted.", [
public function unsuspend(User $user): void
{
Log::alert('A suspension has just been lifted.', [
'target_email' => $user->email,
]);
@@ -61,29 +61,27 @@ class AccountSuspensionService
/**
* Checks whether a user is suspended
*
* @param User $user The user to check
* @param User $user The user to check
* @return bool Whether the mentioned user is suspended
*/
public function isSuspended(User $user): bool {
return !is_null($user->bans);
public function isSuspended(User $user): bool
{
return ! is_null($user->bans);
}
/**
* Sets an administrative lock on a user account.
* Used to prevent logins after a deletion process is initiated, but may be used for
* other things where a suspension is not necessary/warranted, such as a security breach event.
* These locks cannot be overridden manually be administrators.
*
* @param User $user The account to lock
* @param User $user The account to lock
* @return bool
*/
public function lockAccount(User $user): bool
{
Log::alert('User account locked!', [
'email' => $user->email
'email' => $user->email,
]);
$user->administratively_locked = 1;
@@ -92,17 +90,16 @@ class AccountSuspensionService
return $user->save();
}
/**
* Unlocks a user account. Reverse of lockAccount().
*
* @param User $user
* @param User $user
* @return bool
*/
public function unlockAccount(User $user): bool
{
Log::alert('User account unlocked!', [
'email' => $user->email
'email' => $user->email,
]);
$user->administratively_locked = 0;
@@ -114,25 +111,28 @@ class AccountSuspensionService
/**
* Checks whether an account is locked
*
* @param User $user The user to check
* @param User $user The user to check
* @return bool Whether the mentioned account is locked
*/
public function isLocked(User $user): bool {
public function isLocked(User $user): bool
{
return $user->administratively_locked == 1;
}
/**
* Retrieves the reason for the user's suspension.
*
* @param User $user The user account to check
* @param User $user The user account to check
* @return string|bool Reason for the suspension, false if not suspended
*/
public function getSuspensionReason(User $user): string|bool {
public function getSuspensionReason(User $user): string|bool
{
return ($this->isSuspended($user)) ? $user->bans->reason : false;
}
public function getSuspensionDuration(User $user): string|null {
if ($this->isSuspended($user) && !is_null($user->bans->bannedUntil)) {
public function getSuspensionDuration(User $user): string|null
{
if ($this->isSuspended($user) && ! is_null($user->bans->bannedUntil)) {
return $user->bans->bannedUntil->diffForHumans();
}
@@ -149,6 +149,4 @@ class AccountSuspensionService
// Unban on the last day, not on the exact time (with Carbon::now()).
return (bool) Ban::whereDate('bannedUntil', '=', Carbon::today())->delete();
}
}

View File

@@ -1,26 +1,24 @@
<?php
namespace App\Services;
use App\Exceptions\DiscordAccountRequiredException;
use App\Exceptions\IncompatibleAgeException;
use App\Exceptions\InvalidAgeException;
use App\Notifications\ApplicationConfirmed;
use Carbon\Carbon;
use ContextAwareValidator;
use App\Application;
use App\Events\ApplicationDeniedEvent;
use App\Exceptions\ApplicationNotFoundException;
use App\Exceptions\DiscordAccountRequiredException;
use App\Exceptions\IncompatibleAgeException;
use App\Exceptions\IncompleteApplicationException;
use App\Exceptions\InvalidAgeException;
use App\Exceptions\UnavailableApplicationException;
use App\Exceptions\VacancyNotFoundException;
use App\Notifications\ApplicationConfirmed;
use App\Notifications\ApplicationMoved;
use App\Notifications\NewApplicant;
use App\Response;
use App\User;
use App\Vacancy;
use Illuminate\Auth\Authenticatable;
use Carbon\Carbon;
use ContextAwareValidator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
@@ -37,26 +35,23 @@ class ApplicationService
$firstVacancy = $vacancyWithForm->first();
if (is_null(Auth::user()->dob)) {
throw new InvalidAgeException("User must have added their age to apply for this vacancy.");
} elseif(Carbon::parse(Auth::user()->dob)->age < $firstVacancy->requiredAge) {
throw new InvalidAgeException('User must have added their age to apply for this vacancy.');
} elseif (Carbon::parse(Auth::user()->dob)->age < $firstVacancy->requiredAge) {
throw new IncompatibleAgeException("Sorry, you must be {$firstVacancy->requiredAge} or older to apply to {$firstVacancy->vacancyName}.");
}
if ($firstVacancy->requiresDiscord && !Auth::user()->hasDiscordConnection()) {
if ($firstVacancy->requiresDiscord && ! Auth::user()->hasDiscordConnection()) {
throw new DiscordAccountRequiredException('A discord account is required beyond this point.');
}
if (!$vacancyWithForm->isEmpty() && $firstVacancy->vacancyCount !== 0 && $firstVacancy->vacancyStatus == 'OPEN') {
if (! $vacancyWithForm->isEmpty() && $firstVacancy->vacancyCount !== 0 && $firstVacancy->vacancyStatus == 'OPEN') {
return view('dashboard.application-rendering.apply')
->with([
'vacancy' => $vacancyWithForm->first(),
'preprocessedForm' => json_decode($vacancyWithForm->first()->forms->formStructure, true),
]);
} else {
throw new ApplicationNotFoundException(__('The application you\'re looking for could not be found or it is currently unavailable.'), 404);
}
}
@@ -72,14 +67,11 @@ class ApplicationService
$vacancy = Vacancy::with('forms')->where('vacancySlug', $vacancySlug)->get();
if ($vacancy->isEmpty()) {
throw new VacancyNotFoundException('This vacancy doesn\'t exist; Please use the proper buttons to apply to one.', 404);
}
if ($vacancy->first()->vacancyCount == 0 || $vacancy->first()->vacancyStatus !== 'OPEN') {
throw new UnavailableApplicationException("This application is unavailable.");
throw new UnavailableApplicationException('This application is unavailable.');
}
Log::info('Processing new application!');
@@ -87,10 +79,9 @@ class ApplicationService
$formStructure = json_decode($vacancy->first()->forms->formStructure, true);
$responseValidation = ContextAwareValidator::getResponseValidator($formData, $formStructure);
Log::info('Built response & validator structure!');
if (!$responseValidation->get('validator')->fails()) {
if (! $responseValidation->get('validator')->fails()) {
$response = Response::create([
'responseFormID' => $vacancy->first()->forms->id,
'associatedVacancyID' => $vacancy->first()->id, // Since a form can be used by multiple vacancies, we can only know which specific vacancy this response ties to by using a vacancy ID
@@ -99,7 +90,7 @@ class ApplicationService
Log::info('Registered form response!', [
'applicant' => $applicant->name,
'vacancy' => $vacancy->first()->vacancyName
'vacancy' => $vacancy->first()->vacancyName,
]);
$application = Application::create([
@@ -110,7 +101,7 @@ class ApplicationService
Log::info('Submitted an application!', [
'responseID' => $response->id,
'applicant' => $applicant->name
'applicant' => $applicant->name,
]);
User::whereHas('roles', function ($q) {
@@ -122,10 +113,9 @@ class ApplicationService
$application->user->notify(new ApplicationConfirmed($application));
return true;
}
Log::warning('Application form for ' . $applicant->name . ' contained errors, resetting!');
Log::warning('Application form for '.$applicant->name.' contained errors, resetting!');
throw new IncompleteApplicationException('There are one or more errors in your application. Please make sure none of your fields are empty, since they are all required.');
}
@@ -136,12 +126,12 @@ class ApplicationService
case 'deny':
event(new ApplicationDeniedEvent($application));
$message = __("Application denied successfully.");
$message = __('Application denied successfully.');
break;
case 'interview':
Log::info(' Moved application ID ' . $application->id . 'to interview stage!');
Log::info(' Moved application ID '.$application->id.'to interview stage!');
$message = __('Application moved to interview stage!');
$application->setStatus('STAGE_INTERVIEW');
@@ -150,7 +140,7 @@ class ApplicationService
break;
default:
throw new \LogicException("Wrong status parameter. Please notify a developer.");
throw new \LogicException('Wrong status parameter. Please notify a developer.');
}
return $message;
@@ -164,7 +154,6 @@ class ApplicationService
return $application->delete();
}
public function canVote($votes): bool
{
$allvotes = collect([]);
@@ -175,6 +164,6 @@ class ApplicationService
}
}
return !(($allvotes->count() == 1));
return ! (($allvotes->count() == 1));
}
}

View File

@@ -1,13 +1,10 @@
<?php
namespace App\Services;
use App\Application;
use App\Appointment;
use App\Exceptions\InvalidAppointmentStatusException;
use App\Notifications\ApplicationMoved;
use App\Notifications\AppointmentCancelled;
use App\Notifications\AppointmentFinished;
use App\Notifications\AppointmentScheduled;
@@ -30,10 +27,10 @@ class AppointmentService
/**
* Schedules an appointment for the provided application.
*
* @param Application $application The target application.
* @param Carbon $appointmentDate The appointment's date and time.
* @param string $appointmentDescription The appointment description.
* @param string $appointmentLocation The appointment location.
* @param Application $application The target application.
* @param Carbon $appointmentDate The appointment's date and time.
* @param string $appointmentDescription The appointment description.
* @param string $appointmentLocation The appointment location.
* @return bool Whether the appointment was scheduled.
*/
public function createAppointment(Application $application, Carbon $appointmentDate, $appointmentDescription, $appointmentLocation)
@@ -53,22 +50,20 @@ class AppointmentService
$application->user->notify(new AppointmentScheduled($appointment));
return true;
}
/**
* Cancels an appointment for the provided application.
*
* @param Application $application The target application.
* @param string $reason The reason for cancelling the appointment.
* @param Application $application The target application.
* @param string $reason The reason for cancelling the appointment.
*
* @throws \Exception Thrown when there's no appointment to cancel
*/
public function deleteAppointment(Application $application, string $reason): bool
{
if (!empty($application->appointment))
{
if (! empty($application->appointment)) {
$application->user->notify(new AppointmentCancelled($application, Carbon::parse($application->appointment->appointmentDate), $reason));
$application->appointment->delete();
@@ -77,14 +72,13 @@ class AppointmentService
Log::info('An interview appointment has just been cancelled.', [
'actor' => Auth::user()->name,
'applicant' => $application->user->name,
'reason' => $reason
'reason' => $reason,
]);
return true;
}
throw new \Exception("This application doesn't have an appointment!");
}
/**
@@ -97,22 +91,17 @@ class AppointmentService
*/
public function updateAppointment(Application $application, $status, $updateApplication = true)
{
if ($status == 'SCHEDULED' || $status == 'concluded')
{
if ($status == 'SCHEDULED' || $status == 'concluded') {
$application->appointment->appointmentStatus = strtoupper($status);
$application->appointment->save();
if ($updateApplication)
{
if ($updateApplication) {
$application->setStatus('STAGE_PEERAPPROVAL');
$application->user->notify(new AppointmentFinished($application->appointment));
}
} else {
throw new InvalidAppointmentStatusException('Invalid appointment status!');
}
else
{
throw new InvalidAppointmentStatusException("Invalid appointment status!");
}
}
/**
@@ -122,5 +111,4 @@ class AppointmentService
{
return $this->allowedPlatforms;
}
}

View File

@@ -1,17 +1,15 @@
<?php
namespace App\Services;
use App\Application;
use App\Comment;
use Illuminate\Support\Facades\Auth;
class CommentService
{
public function addComment(Application $application, $comment): Comment {
public function addComment(Application $application, $comment): Comment
{
return Comment::create([
'authorID' => Auth::user()->id,
'applicationID' => $application->id,
@@ -23,5 +21,4 @@ class CommentService
{
return $comment->delete();
}
}

View File

@@ -1,28 +1,21 @@
<?php
namespace App\Services;
use App\Exceptions\InvalidGamePreferenceException;
use App\Exceptions\OptionNotFoundException;
use App\Facades\Options;
use Illuminate\Auth\Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class ConfigurationService
{
/**
* @throws OptionNotFoundException|\Exception
*
*/
public function saveConfiguration($configuration) {
public function saveConfiguration($configuration)
{
foreach ($configuration as $optionName => $option) {
try {
Log::debug('Going through option '.$optionName);
if (Options::optionExists($optionName)) {
Log::debug('Option exists, updating to new values', [
@@ -31,9 +24,7 @@ class ConfigurationService
]);
Options::changeOption($optionName, $option);
}
} catch (\Exception $ex) {
Log::error('Unable to update options!', [
'msg' => $ex->getMessage(),
'trace' => $ex->getTraceAsString(),
@@ -49,27 +40,26 @@ class ConfigurationService
* Saves the chosen game integration
*
* @throws InvalidGamePreferenceException
*
* @returns bool
*/
public function saveGameIntegration($gamePreference): bool
{
// TODO: Find solution to dynamically support games
$supportedGames = [
'RUST',
'MINECRAFT',
'SE',
'GMOD'
'GMOD',
];
if (!is_null($gamePreference) && in_array($gamePreference, $supportedGames))
{
if (! is_null($gamePreference) && in_array($gamePreference, $supportedGames)) {
Options::changeOption('currentGame', $gamePreference);
return true;
}
throw new InvalidGamePreferenceException("Unsupported game " . $gamePreference);
throw new InvalidGamePreferenceException('Unsupported game '.$gamePreference);
}
}

View File

@@ -1,9 +1,7 @@
<?php
namespace App\Services;
use App\Exceptions\FailedCaptchaException;
use App\Notifications\NewContact;
use App\User;
@@ -11,7 +9,6 @@ use Illuminate\Support\Facades\Http;
class ContactService
{
/**
* Sends a message to all admins.
*
@@ -42,6 +39,4 @@ class ContactService
}
}
}
}

View File

@@ -1,11 +1,11 @@
<?php
namespace App\Services;
class DemoService {
public function isDemoEnabled(): bool {
class DemoService
{
public function isDemoEnabled(): bool
{
return config('demo.is_enabled');
}
}

View File

@@ -4,31 +4,29 @@ namespace App\Services;
use App\User;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
class DiscordService
{
/**
* Sends a token revocation request to Discord to invalidate a specific $user's tokens.
* Please ensure you have the user set a password for their account after this, or request new tokens.
*
* @see https://www.rfc-editor.org/rfc/rfc7009
* @param User $user
*
* @param User $user
* @return bool
*
* @throws RequestException
*/
public function revokeAccountTokens(User $user): bool
{
$req = Http::asForm()->post(config('services.discord.base_url') . '/oauth2/token/revoke', [
$req = Http::asForm()->post(config('services.discord.base_url').'/oauth2/token/revoke', [
'client_id' => config('services.discord.client_id'),
'client_secret' => config('services.discord.client_secret'),
'token' => $user->discord_token,
])->throw();
$user->discord_token = null;
$user->discord_user_id = null;
$user->discord_refresh_token = null;
@@ -37,6 +35,4 @@ class DiscordService
return $req->ok();
}
}

View File

@@ -1,6 +1,5 @@
<?php
namespace App\Services;
use App\Exceptions\EmptyFormException;
@@ -10,9 +9,8 @@ use ContextAwareValidator;
class FormManagementService
{
public function addForm($fields) {
public function addForm($fields)
{
if (count($fields) == 2) {
// form is probably empty, since forms with fields will always have more than 2 items
throw new EmptyFormException('Sorry, but you may not create empty forms.');
@@ -30,13 +28,15 @@ class FormManagementService
'formStatus' => 'ACTIVE',
]
);
return true;
}
return $contextValidation->get('validator')->errors()->getMessages();
}
public function deleteForm(Form $form) {
public function deleteForm(Form $form)
{
$deletable = true;
if (! is_null($form->vacancies) && $form->vacancies->count() !== 0 || ! is_null($form->responses)) {
@@ -44,19 +44,16 @@ class FormManagementService
}
if ($deletable) {
$form->delete();
return true;
} else {
throw new FormHasConstraintsException(__('You cannot delete this form because it\'s tied to one or more applications and ranks, or because it doesn\'t exist.'));
}
}
public function updateForm(Form $form, $fields) {
public function updateForm(Form $form, $fields)
{
$contextValidation = ContextAwareValidator::getValidator($fields, true);
if (! $contextValidation->get('validator')->fails()) {
@@ -67,10 +64,8 @@ class FormManagementService
$form->save();
return $form;
} else {
return $contextValidation->get('validator')->errors()->getMessages();
}
}
}

View File

@@ -1,9 +1,7 @@
<?php
namespace App\Services;
use App\Application;
use App\Exceptions\InvalidAppointmentException;
@@ -12,13 +10,14 @@ class MeetingNoteService
/**
* Adds meeting notes to an application.
*
* @param Application $application
* @param Application $application
* @param $noteText
* @return bool
*
* @throws InvalidAppointmentException Thrown when an application doesn't have an appointment to save notes to
*/
public function addToApplication(Application $application, $noteText): bool {
public function addToApplication(Application $application, $noteText): bool
{
if (! is_null($application)) {
$application->load('appointment');
@@ -26,11 +25,8 @@ class MeetingNoteService
$application->appointment->save();
return true;
} else {
throw new InvalidAppointmentException('There\'s no appointment to save notes to!');
}
}
}

View File

@@ -1,33 +1,29 @@
<?php
namespace App\Services;
use App\Exceptions\ProfileAlreadyExistsException;
use App\Exceptions\ProfileCreationFailedException;
use App\Exceptions\ProfileNotFoundException;
use App\Profile;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class ProfileService
{
/**
* Creates a new profile for the specified $targetUser.
*
* @param User $targetUser The user to create the profile for.
* @param User $targetUser The user to create the profile for.
* @return bool
*
* @throws ProfileAlreadyExistsException
* @throws ProfileCreationFailedException
*/
public function createProfile(User $targetUser): Profile {
public function createProfile(User $targetUser): Profile
{
if (is_null($targetUser->profile)) {
$profile = Profile::create([
'profileShortBio' => 'Write a one-liner about you here!',
@@ -42,7 +38,7 @@ class ProfileService
}
Log::info('Created profile for new user', [
'userid' => $targetUser->id
'userid' => $targetUser->id,
]);
return $profile;
@@ -56,7 +52,8 @@ class ProfileService
*
* @throws ProfileNotFoundException
*/
public function updateProfile($userID, Request $request) {
public function updateProfile($userID, Request $request)
{
$profile = User::find($userID)->profile;
$social = [];
@@ -85,23 +82,22 @@ class ProfileService
return $profile->save();
}
throw new ProfileNotFoundException("This profile does not exist.");
throw new ProfileNotFoundException('This profile does not exist.');
}
/**
* Delete specified user's profile
*
* @param User $targetUser
* @param User $targetUser
* @return bool
*
* @throws ProfileNotFoundException
*/
public function deleteProfile(User $targetUser): bool
{
if (!is_null($targetUser->profile)) {
if (! is_null($targetUser->profile)) {
Log::alert('Deleted user profile', [
'userid' => $targetUser->id
'userid' => $targetUser->id,
]);
return $targetUser->profile->delete();
@@ -109,5 +105,4 @@ class ProfileService
throw new ProfileNotFoundException(__('Attempting to delete non-existant profile!'));
}
}

View File

@@ -1,44 +1,38 @@
<?php
namespace App\Services;
use App\Facades\Options;
use Illuminate\Support\Facades\Log;
class SecuritySettingsService
{
/**
* Saves the app security settings.
*
* @param $policy
* @param array $options
* @param array $options
* @return bool
*/
public function save($policy, $options = []) {
public function save($policy, $options = [])
{
$validPolicies = [
'off',
'low',
'medium',
'high'
'high',
];
if (in_array($policy, $validPolicies))
{
if (in_array($policy, $validPolicies)) {
Options::changeOption('pw_security_policy', $policy);
Log::debug('[Options] Changing option pw_security_policy', [
'new_value' => $policy
'new_value' => $policy,
]);
}
else
{
} else {
Log::debug('[WARN] Ignoring bogus policy', [
'avaliable' => $validPolicies,
'given' => $policy
'given' => $policy,
]);
}
@@ -48,7 +42,5 @@ class SecuritySettingsService
Options::changeOption('requireGameLicense', $options['requirePMC']);
return true;
}
}

View File

@@ -1,19 +1,15 @@
<?php
namespace App\Services;
use App\Exceptions\FileUploadException;
use App\TeamFile;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
class TeamFileService
{
public function addFile(UploadedFile $upload, $uploader, $team, $caption, $description) {
public function addFile(UploadedFile $upload, $uploader, $team, $caption, $description)
{
$file = $upload->store('uploads');
$originalFileName = $upload->getClientOriginalName();
$originalFileExtension = $upload->extension();
@@ -27,16 +23,13 @@ class TeamFileService
'description' => $description,
'fs_location' => $file,
'extension' => $originalFileExtension,
'size' => $originalFileSize
'size' => $originalFileSize,
]);
if ($fileEntry && !is_bool($file))
{
return $fileEntry;
if ($fileEntry && ! is_bool($file)) {
return $fileEntry;
}
throw new FileUploadException("There was an unknown error whilst trying to upload your file.");
throw new FileUploadException('There was an unknown error whilst trying to upload your file.');
}
}

View File

@@ -1,9 +1,7 @@
<?php
namespace App\Services;
use App\Exceptions\InvalidInviteException;
use App\Exceptions\PublicTeamInviteException;
use App\Exceptions\UserAlreadyInvitedException;
@@ -18,7 +16,6 @@ use Mpociot\Teamwork\TeamInvite;
class TeamService
{
/**
* Create a team
*
@@ -26,8 +23,8 @@ class TeamService
* @param $ownerID
* @return Team
*/
public function createTeam($teamName, $ownerID): Team {
public function createTeam($teamName, $ownerID): Team
{
$team = Team::create([
'name' => $teamName,
'owner_id' => $ownerID,
@@ -40,7 +37,6 @@ class TeamService
public function updateTeam(Team $team, $teamDescription, $joinType): bool
{
$team->description = $teamDescription;
$team->openJoin = $joinType;
@@ -55,7 +51,6 @@ class TeamService
*/
public function inviteUser(Team $team, $userID): bool
{
$user = User::findOrFail($userID);
if (! $team->openJoin) {
@@ -63,6 +58,7 @@ class TeamService
Teamwork::inviteToTeam($user, $team, function (TeamInvite $invite) use ($user) {
Mail::to($user)->send(new InviteToTeam($invite));
});
return true;
} else {
throw new UserAlreadyInvitedException('This user has already been invited.');
@@ -70,20 +66,20 @@ class TeamService
} else {
throw new PublicTeamInviteException('You can\'t invite users to public teams.');
}
}
/**
* Accepts or denies a user invite
*
* @param Authenticatable $user
* @param Authenticatable $user
* @param $action
* @param $token
* @return bool True on success or exception on failure
*
* @throws InvalidInviteException Thrown when the invite code / url is invalid
*/
public function processInvite(Authenticatable $user, $action, $token): bool {
public function processInvite(Authenticatable $user, $action, $token): bool
{
switch ($action) {
case 'accept':
@@ -91,9 +87,7 @@ class TeamService
if ($invite && $invite->user->is($user)) {
Teamwork::acceptInvite($invite);
} else {
throw new InvalidInviteException('Invalid or expired invite URL.');
}
@@ -104,11 +98,8 @@ class TeamService
$invite = Teamwork::getInviteFromDenyToken($token);
if ($invite && $invite->user->is($user)) {
Teamwork::denyInvite($invite);
} else {
throw new InvalidInviteException('Invalid or expired invite URL.');
}
@@ -119,18 +110,15 @@ class TeamService
}
return true;
}
/**
* @param Team $team
* @param Team $team
* @param $associatedVacancies
* @return string The success message, exception/bool if error
*/
public function updateVacancies(Team $team, $associatedVacancies): string
{
// P.S. To future developers
// This method gave me a lot of trouble lol. It's hard to write code when you're half asleep.
// There may be an n+1 query in the view and I don't think there's a way to avoid that without writing a lot of extra code.
@@ -160,6 +148,7 @@ class TeamService
} else {
$team->vacancies()->attach($requestVacancies);
}
return 'Assignments changed successfully.';
}
}

View File

@@ -29,7 +29,7 @@ class VacancyApplicationService
/**
* Finds all applications associated with $model.
*
* @param Vacancy $model The model you want to search through.
* @param Vacancy $model The model you want to search through.
* @return Illuminate\Support\Collection A collection of applications
*/
public function findApplications(Vacancy $model)