From 4ff5adc2a60237c0b3b005056608b909741403e7 Mon Sep 17 00:00:00 2001 From: Lance Pioch Date: Thu, 9 Jul 2026 09:55:11 -0400 Subject: [PATCH] Monthly Shift: July 2026 (#2433) Co-authored-by: Shift --- app/Checks/ScheduleCheck.php | 2 +- .../Commands/Egg/CheckEggUpdatesCommand.php | 8 +--- .../Commands/Egg/NormalizeEggCommand.php | 2 +- .../CleanServiceBackupFilesCommand.php | 2 +- .../PruneOrphanedBackupsCommand.php | 4 +- .../Schemas/Turnstile/TurnstileSchema.php | 8 +--- app/Filament/Admin/Pages/Health.php | 2 +- .../Resources/Plugins/PluginResource.php | 8 +--- .../Admin/Resources/Users/UserResource.php | 2 +- .../Components/Actions/UploadIcon.php | 20 ++------ .../Components/Forms/Fields/MonacoEditor.php | 4 +- app/Filament/Pages/Auth/EditProfile.php | 2 +- .../Resources/Files/Pages/ListFiles.php | 4 +- .../Resources/Schedules/ScheduleResource.php | 2 +- app/Filament/Server/Widgets/ServerConsole.php | 4 +- .../Server/Widgets/ServerCpuChart.php | 2 +- .../Server/Widgets/ServerMemoryChart.php | 2 +- .../Server/Widgets/ServerNetworkChart.php | 2 +- app/Helpers/Utilities.php | 2 +- .../Application/Mounts/MountController.php | 4 +- .../Application/Plugins/PluginController.php | 24 +++------- .../Api/Application/Roles/RoleController.php | 8 +--- .../Api/Client/AccountController.php | 4 +- .../Api/Client/ApiKeyController.php | 4 +- .../Api/Client/Servers/BackupController.php | 28 +++-------- .../Api/Client/Servers/CommandController.php | 4 +- .../Servers/NetworkAllocationController.php | 8 +--- .../Servers/ResourceUtilizationController.php | 2 +- .../Api/Client/Servers/ScheduleController.php | 6 +-- .../Client/Servers/ScheduleTaskController.php | 24 +++------- .../Api/Client/Servers/SettingsController.php | 4 +- .../Api/Client/Servers/StartupController.php | 8 ++-- .../Client/Servers/WebsocketController.php | 8 +--- .../Remote/ActivityProcessingController.php | 2 +- .../Backups/BackupRemoteUploadController.php | 4 +- .../Remote/Backups/BackupStatusController.php | 12 ++--- .../Servers/ServerContainersController.php | 4 +- .../Servers/ServerDetailsController.php | 4 +- .../Servers/ServerInstallController.php | 8 +--- .../Servers/ServerTransferController.php | 16 ++----- .../Remote/SftpAuthenticationController.php | 4 +- .../AuthenticateApplicationUser.php | 4 +- .../Api/Client/RequireClientApiKey.php | 4 +- .../Server/AuthenticateServerAccess.php | 16 ++----- .../Client/Server/ResourceBelongsToServer.php | 16 ++----- .../Api/Daemon/DaemonAuthenticate.php | 8 +--- .../RequireTwoFactorAuthentication.php | 4 +- .../Api/Application/ApplicationApiRequest.php | 4 +- .../Api/Client/Account/StoreSSHKeyRequest.php | 4 +- .../Api/Client/Account/UpdateEmailRequest.php | 4 +- .../Client/Account/UpdatePasswordRequest.php | 4 +- .../Client/Account/UpdateUsernameRequest.php | 4 +- .../Servers/Schedules/ViewScheduleRequest.php | 4 +- .../Servers/Subusers/SubuserRequest.php | 4 +- app/Jobs/Schedule/RunTaskJob.php | 10 ++-- app/Livewire/Installer/Steps/CacheStep.php | 4 +- app/Livewire/Installer/Steps/DatabaseStep.php | 4 +- app/Models/ActivityLog.php | 4 +- app/Models/Filters/MultiFieldServerFilter.php | 4 +- app/Models/Plugin.php | 8 +--- app/Models/Server.php | 10 ++-- app/Models/Traits/HasIcon.php | 8 +--- app/Models/WebhookConfiguration.php | 2 +- .../Daemon/DaemonFileRepository.php | 20 ++------ app/Repositories/Daemon/DaemonRepository.php | 8 +--- .../Daemon/DaemonSystemRepository.php | 4 +- .../Allocations/AssignmentService.php | 20 ++------ .../FindAssignableAllocationService.php | 16 ++----- app/Services/Backups/DeleteBackupService.php | 4 +- .../Backups/InitiateBackupService.php | 8 +--- .../Databases/DatabaseManagementService.php | 16 ++----- .../Databases/DeployServerDatabaseService.php | 8 +--- .../Deployment/AllocationSelectionService.php | 8 +--- .../Eggs/Sharing/EggExporterService.php | 2 +- .../Eggs/Sharing/EggImporterService.php | 8 +--- .../Variables/VariableCreationService.php | 4 +- .../Eggs/Variables/VariableUpdateService.php | 8 +--- app/Services/Helpers/PluginService.php | 48 +++++-------------- app/Services/Nodes/NodeDeletionService.php | 4 +- app/Services/Nodes/NodeUpdateService.php | 4 +- .../Schedules/ProcessScheduleService.php | 4 +- .../Sharing/ScheduleImporterService.php | 8 +--- .../Servers/ServerCreationService.php | 4 +- app/Services/Servers/ToggleInstallService.php | 4 +- .../Servers/VariableValidatorService.php | 4 +- app/Services/Ssh/KeyCreationService.php | 12 ++--- .../Subusers/SubuserCreationService.php | 8 +--- app/Traits/HasValidation.php | 4 +- .../Api/Client/EggVariableTransformer.php | 4 +- .../Api/Client/FileObjectTransformer.php | 2 +- database/Factories/ApiKeyFactory.php | 2 +- database/Factories/DatabaseFactory.php | 2 +- database/Factories/ServerFactory.php | 2 +- database/Factories/UserFactory.php | 2 +- ..._002938_TransferOldTasksToNewScheduler.php | 2 +- ...628_RemoveDaemonSecretFromServersTable.php | 2 +- ...22_RemoveDaemonSecretFromSubusersTable.php | 2 +- ...1922_Add2FaLastAuthorizationTimeColumn.php | 2 +- ..._07_19_130942_create_permission_tables.php | 12 ++--- .../Jobs/Schedule/RunTaskJobTest.php | 2 +- tests/TestCase.php | 2 +- tests/Traits/Http/MocksMiddlewareClosure.php | 4 +- tests/Traits/Http/RequestMockHelpers.php | 4 +- .../Commands/Egg/NormalizerEggCommandTest.php | 13 ++--- 104 files changed, 192 insertions(+), 511 deletions(-) diff --git a/app/Checks/ScheduleCheck.php b/app/Checks/ScheduleCheck.php index be7583914..8bb6b3693 100644 --- a/app/Checks/ScheduleCheck.php +++ b/app/Checks/ScheduleCheck.php @@ -2,8 +2,8 @@ namespace App\Checks; -use Carbon\Carbon; use Composer\InstalledVersions; +use Illuminate\Support\Carbon; use Spatie\Health\Checks\Checks\ScheduleCheck as BaseCheck; use Spatie\Health\Checks\Result; diff --git a/app/Console/Commands/Egg/CheckEggUpdatesCommand.php b/app/Console/Commands/Egg/CheckEggUpdatesCommand.php index 45f687ef4..4dd659d9d 100644 --- a/app/Console/Commands/Egg/CheckEggUpdatesCommand.php +++ b/app/Console/Commands/Egg/CheckEggUpdatesCommand.php @@ -37,9 +37,7 @@ class CheckEggUpdatesCommand extends Command $extension = strtolower(pathinfo(parse_url($egg->update_url, PHP_URL_PATH), PATHINFO_EXTENSION)); - if (empty($extension)) { - throw new Exception('Unsupported file format.'); - } + throw_if(empty($extension), new Exception('Unsupported file format.')); $isYaml = in_array($extension, ['yaml', 'yml']); @@ -49,9 +47,7 @@ class CheckEggUpdatesCommand extends Command $remote = Http::timeout(5)->connectTimeout(1)->get($egg->update_url); - if ($remote->failed()) { - throw new Exception("HTTP request returned status code {$remote->status()}"); - } + throw_if($remote->failed(), new Exception("HTTP request returned status code {$remote->status()}")); $remote = $remote->body(); $remote = $isYaml ? Yaml::parse($remote) : json_decode($remote, true); diff --git a/app/Console/Commands/Egg/NormalizeEggCommand.php b/app/Console/Commands/Egg/NormalizeEggCommand.php index cbe60ca3d..6d99f72c7 100644 --- a/app/Console/Commands/Egg/NormalizeEggCommand.php +++ b/app/Console/Commands/Egg/NormalizeEggCommand.php @@ -7,8 +7,8 @@ use App\Exceptions\Service\InvalidFileUploadException; use App\Models\Egg; use App\Services\Eggs\Sharing\EggExporterService; use App\Services\Eggs\Sharing\EggImporterService; -use Carbon\Carbon; use Illuminate\Console\Command; +use Illuminate\Support\Carbon; use Symfony\Component\Yaml\Yaml; class NormalizeEggCommand extends Command diff --git a/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php b/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php index 876c9fce9..467543f67 100644 --- a/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php +++ b/app/Console/Commands/Maintenance/CleanServiceBackupFilesCommand.php @@ -2,10 +2,10 @@ namespace App\Console\Commands\Maintenance; -use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory; use Illuminate\Contracts\Filesystem\Filesystem; +use Illuminate\Support\Carbon; use SplFileInfo; class CleanServiceBackupFilesCommand extends Command diff --git a/app/Console/Commands/Maintenance/PruneOrphanedBackupsCommand.php b/app/Console/Commands/Maintenance/PruneOrphanedBackupsCommand.php index 9cb49f643..d726a5a4f 100644 --- a/app/Console/Commands/Maintenance/PruneOrphanedBackupsCommand.php +++ b/app/Console/Commands/Maintenance/PruneOrphanedBackupsCommand.php @@ -16,9 +16,7 @@ class PruneOrphanedBackupsCommand extends Command public function handle(): void { $since = $this->option('prune-age') ?? config('backups.prune_age', 360); - if (!$since || !is_digit($since)) { - throw new InvalidArgumentException('The "--prune-age" argument must be a value greater than 0.'); - } + throw_if(!$since || !is_digit($since), new InvalidArgumentException('The "--prune-age" argument must be a value greater than 0.')); $query = Backup::query() ->whereNull('completed_at') diff --git a/app/Extensions/Captcha/Schemas/Turnstile/TurnstileSchema.php b/app/Extensions/Captcha/Schemas/Turnstile/TurnstileSchema.php index f6220b2fe..c39fe8f71 100644 --- a/app/Extensions/Captcha/Schemas/Turnstile/TurnstileSchema.php +++ b/app/Extensions/Captcha/Schemas/Turnstile/TurnstileSchema.php @@ -75,9 +75,7 @@ class TurnstileSchema extends BaseSchema implements CaptchaSchemaInterface { $captchaResponse ??= request()->get('cf-turnstile-response'); - if (!$secret = env('CAPTCHA_TURNSTILE_SECRET_KEY')) { - throw new Exception('Turnstile secret key is not defined.'); - } + throw_unless($secret = env('CAPTCHA_TURNSTILE_SECRET_KEY'), new Exception('Turnstile secret key is not defined.')); $response = Http::asJson() ->timeout(15) @@ -101,9 +99,7 @@ class TurnstileSchema extends BaseSchema implements CaptchaSchemaInterface }; } - if (!$this->verifyDomain($response['hostname'] ?? '')) { - throw new Exception('Domain verification failed.'); - } + throw_unless($this->verifyDomain($response['hostname'] ?? ''), new Exception('Domain verification failed.')); } private function verifyDomain(string $hostname): bool diff --git a/app/Filament/Admin/Pages/Health.php b/app/Filament/Admin/Pages/Health.php index 7518d5ab7..c7c12652b 100644 --- a/app/Filament/Admin/Pages/Health.php +++ b/app/Filament/Admin/Pages/Health.php @@ -4,10 +4,10 @@ namespace App\Filament\Admin\Pages; use App\Enums\TablerIcon; use BackedEnum; -use Carbon\Carbon; use Filament\Actions\Action; use Filament\Notifications\Notification; use Filament\Pages\Page; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Artisan; use Spatie\Health\Commands\RunHealthChecksCommand; use Spatie\Health\Enums\Status; diff --git a/app/Filament/Admin/Resources/Plugins/PluginResource.php b/app/Filament/Admin/Resources/Plugins/PluginResource.php index 7c0f18140..d78e85b59 100644 --- a/app/Filament/Admin/Resources/Plugins/PluginResource.php +++ b/app/Filament/Admin/Resources/Plugins/PluginResource.php @@ -265,9 +265,7 @@ class PluginResource extends Resource $pluginName = str($file->getClientOriginalName())->basename()->before('.zip')->toString(); - if (Plugin::where('id', $pluginName)->exists()) { - throw new Exception(trans('admin/plugin.notifications.import_exists')); - } + throw_if(Plugin::where('id', $pluginName)->exists(), new Exception(trans('admin/plugin.notifications.import_exists'))); $pluginService->downloadPluginFromFile($file); @@ -304,9 +302,7 @@ class PluginResource extends Resource try { $pluginName = str($data['url'])->before('.zip')->explode('/')->last(); - if (Plugin::where('id', $pluginName)->exists()) { - throw new Exception(trans('admin/plugin.notifications.import_exists')); - } + throw_if(Plugin::where('id', $pluginName)->exists(), new Exception(trans('admin/plugin.notifications.import_exists'))); $pluginService->downloadPluginFromUrl($data['url']); diff --git a/app/Filament/Admin/Resources/Users/UserResource.php b/app/Filament/Admin/Resources/Users/UserResource.php index 001ef63ca..f089a9aa3 100644 --- a/app/Filament/Admin/Resources/Users/UserResource.php +++ b/app/Filament/Admin/Resources/Users/UserResource.php @@ -481,7 +481,7 @@ class UserResource extends Resource ->deletable(false) ->addable(false) ->relationship(null, function (Builder $query) { - $query->orderBy('timestamp', 'desc'); + $query->orderByDesc('timestamp'); }) ->schema([ TextEntry::make('log') diff --git a/app/Filament/Components/Actions/UploadIcon.php b/app/Filament/Components/Actions/UploadIcon.php index a18593504..dd44865e5 100644 --- a/app/Filament/Components/Actions/UploadIcon.php +++ b/app/Filament/Components/Actions/UploadIcon.php @@ -104,15 +104,11 @@ class UploadIcon extends Action $content = Http::timeout(5)->connectTimeout(1)->withoutRedirecting()->get($data['icon_url'])->body(); - if (empty($content)) { - throw new Exception(trans('admin/egg.import.invalid_url')); - } + throw_if(empty($content), new Exception(trans('admin/egg.import.invalid_url'))); $extension = strtolower(pathinfo(parse_url($data['icon_url'], PHP_URL_PATH), PATHINFO_EXTENSION)); - if (empty($extension)) { - throw new Exception(trans('admin/egg.import.invalid_url')); - } + throw_if(empty($extension), new Exception(trans('admin/egg.import.invalid_url'))); $record->writeIcon($extension, $content); @@ -136,20 +132,14 @@ class UploadIcon extends Action protected function validateIconUrl(string $url): void { - if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) { - throw new Exception(trans('admin/egg.import.invalid_url')); - } + throw_unless(in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true), new Exception(trans('admin/egg.import.invalid_url'))); - if (!filter_var($url, FILTER_VALIDATE_URL)) { - throw new Exception(trans('admin/egg.import.invalid_url')); - } + throw_unless(filter_var($url, FILTER_VALIDATE_URL), new Exception(trans('admin/egg.import.invalid_url'))); $host = parse_url($url, PHP_URL_HOST); $ip = gethostbyname($host); - if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { - throw new Exception(trans('admin/egg.import.no_local_ip')); - } + throw_if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false, new Exception(trans('admin/egg.import.no_local_ip'))); } /** @param string[] $iconFormats */ diff --git a/app/Filament/Components/Forms/Fields/MonacoEditor.php b/app/Filament/Components/Forms/Fields/MonacoEditor.php index 78ecb1ad6..532e16ad6 100644 --- a/app/Filament/Components/Forms/Fields/MonacoEditor.php +++ b/app/Filament/Components/Forms/Fields/MonacoEditor.php @@ -36,9 +36,7 @@ class MonacoEditor extends Field { $theme = $this->evaluate($this->theme); - if (!isset(config('monaco-editor.themes')[$theme])) { - throw new Exception("Theme {$theme} not found in config file."); - } + throw_unless(isset(config('monaco-editor.themes')[$theme]), new Exception("Theme {$theme} not found in config file.")); return json_encode([ 'base' => config("monaco-editor.themes.{$theme}.base"), diff --git a/app/Filament/Pages/Auth/EditProfile.php b/app/Filament/Pages/Auth/EditProfile.php index 8bc815533..0414ef74c 100644 --- a/app/Filament/Pages/Auth/EditProfile.php +++ b/app/Filament/Pages/Auth/EditProfile.php @@ -448,7 +448,7 @@ class EditProfile extends BaseEditProfile ->deletable(false) ->addable(false) ->relationship(null, function (Builder $query) { - $query->orderBy('timestamp', 'desc')->limit(50); + $query->orderByDesc('timestamp')->limit(50); }) ->schema([ TextEntry::make('log') diff --git a/app/Filament/Server/Resources/Files/Pages/ListFiles.php b/app/Filament/Server/Resources/Files/Pages/ListFiles.php index 08ad37543..c0eb2f771 100644 --- a/app/Filament/Server/Resources/Files/Pages/ListFiles.php +++ b/app/Filament/Server/Resources/Files/Pages/ListFiles.php @@ -632,9 +632,7 @@ class ListFiles extends ListRecords /** @var Server $server */ $server = Filament::getTenant(); - if (!user()?->can(SubuserPermission::FileCreate, $server)) { - abort(403, 'You do not have permission to create folders.'); - } + abort_unless(user()?->can(SubuserPermission::FileCreate, $server), 403, 'You do not have permission to create folders.'); try { $this->getDaemonFileRepository()->createDirectory($folderPath, $this->path); diff --git a/app/Filament/Server/Resources/Schedules/ScheduleResource.php b/app/Filament/Server/Resources/Schedules/ScheduleResource.php index 20f9197cf..77f6e5f9b 100644 --- a/app/Filament/Server/Resources/Schedules/ScheduleResource.php +++ b/app/Filament/Server/Resources/Schedules/ScheduleResource.php @@ -21,7 +21,6 @@ use App\Traits\Filament\CanCustomizeRelations; use App\Traits\Filament\CanModifyForm; use App\Traits\Filament\CanModifyTable; use BackedEnum; -use Carbon\Carbon; use Exception; use Filament\Actions\CreateAction; use Filament\Actions\DeleteAction; @@ -45,6 +44,7 @@ use Filament\Support\Exceptions\Halt; use Filament\Tables\Columns\IconColumn; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; +use Illuminate\Support\Carbon; use Illuminate\Support\HtmlString; use Throwable; diff --git a/app/Filament/Server/Widgets/ServerConsole.php b/app/Filament/Server/Widgets/ServerConsole.php index 7a909a3f0..c8c6e73da 100644 --- a/app/Filament/Server/Widgets/ServerConsole.php +++ b/app/Filament/Server/Widgets/ServerConsole.php @@ -47,9 +47,7 @@ class ServerConsole extends Widget protected function getToken(): string { - if (!$this->user || !$this->server || $this->user->cannot(SubuserPermission::WebsocketConnect, $this->server)) { - throw new HttpForbiddenException('You do not have permission to connect to this server\'s websocket.'); - } + throw_if(!$this->user || !$this->server || $this->user->cannot(SubuserPermission::WebsocketConnect, $this->server), new HttpForbiddenException('You do not have permission to connect to this server\'s websocket.')); $permissions = $this->getUserPermissionsService->handle($this->server, $this->user); diff --git a/app/Filament/Server/Widgets/ServerCpuChart.php b/app/Filament/Server/Widgets/ServerCpuChart.php index 8b0f0c36b..7cc0b2e2f 100644 --- a/app/Filament/Server/Widgets/ServerCpuChart.php +++ b/app/Filament/Server/Widgets/ServerCpuChart.php @@ -4,10 +4,10 @@ namespace App\Filament\Server\Widgets; use App\Enums\CustomizationKey; use App\Models\Server; -use Carbon\Carbon; use Filament\Facades\Filament; use Filament\Support\RawJs; use Filament\Widgets\ChartWidget; +use Illuminate\Support\Carbon; class ServerCpuChart extends ChartWidget { diff --git a/app/Filament/Server/Widgets/ServerMemoryChart.php b/app/Filament/Server/Widgets/ServerMemoryChart.php index 5fb787e9a..535d8b9f7 100644 --- a/app/Filament/Server/Widgets/ServerMemoryChart.php +++ b/app/Filament/Server/Widgets/ServerMemoryChart.php @@ -4,10 +4,10 @@ namespace App\Filament\Server\Widgets; use App\Enums\CustomizationKey; use App\Models\Server; -use Carbon\Carbon; use Filament\Facades\Filament; use Filament\Support\RawJs; use Filament\Widgets\ChartWidget; +use Illuminate\Support\Carbon; class ServerMemoryChart extends ChartWidget { diff --git a/app/Filament/Server/Widgets/ServerNetworkChart.php b/app/Filament/Server/Widgets/ServerNetworkChart.php index 10d0cc632..cbe112c75 100644 --- a/app/Filament/Server/Widgets/ServerNetworkChart.php +++ b/app/Filament/Server/Widgets/ServerNetworkChart.php @@ -4,10 +4,10 @@ namespace App\Filament\Server\Widgets; use App\Enums\CustomizationKey; use App\Models\Server; -use Carbon\Carbon; use Filament\Facades\Filament; use Filament\Support\RawJs; use Filament\Widgets\ChartWidget; +use Illuminate\Support\Carbon; class ServerNetworkChart extends ChartWidget { diff --git a/app/Helpers/Utilities.php b/app/Helpers/Utilities.php index cef0ccff2..15a526dcf 100644 --- a/app/Helpers/Utilities.php +++ b/app/Helpers/Utilities.php @@ -2,9 +2,9 @@ namespace App\Helpers; -use Carbon\Carbon; use Cron\CronExpression; use Exception; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; use Illuminate\Support\ViewErrorBag; diff --git a/app/Http/Controllers/Api/Application/Mounts/MountController.php b/app/Http/Controllers/Api/Application/Mounts/MountController.php index 0d9c4d2ad..be075fa92 100644 --- a/app/Http/Controllers/Api/Application/Mounts/MountController.php +++ b/app/Http/Controllers/Api/Application/Mounts/MountController.php @@ -115,9 +115,7 @@ class MountController extends ApplicationApiController */ public function delete(DeleteMountRequest $request, Mount $mount): JsonResponse { - if ($mount->servers()->count() > 0) { - throw new HasActiveServersException(trans('exceptions.mount.servers_attached')); - } + throw_if($mount->servers()->count() > 0, new HasActiveServersException(trans('exceptions.mount.servers_attached'))); $mount->delete(); diff --git a/app/Http/Controllers/Api/Application/Plugins/PluginController.php b/app/Http/Controllers/Api/Application/Plugins/PluginController.php index 8697414e2..ed921f4e9 100644 --- a/app/Http/Controllers/Api/Application/Plugins/PluginController.php +++ b/app/Http/Controllers/Api/Application/Plugins/PluginController.php @@ -68,9 +68,7 @@ class PluginController extends ApplicationApiController */ public function importFile(WritePluginRequest $request): Response { - if (!$request->hasFile('plugin')) { - throw new PanelException("No 'plugin' file in request"); - } + throw_unless($request->hasFile('plugin'), new PanelException("No 'plugin' file in request")); $this->pluginService->downloadPluginFromFile($request->file('plugin')); @@ -102,9 +100,7 @@ class PluginController extends ApplicationApiController */ public function install(WritePluginRequest $request, Plugin $plugin): array { - if ($plugin->status !== PluginStatus::NotInstalled) { - throw new PanelException('Plugin is already installed'); - } + throw_if($plugin->status !== PluginStatus::NotInstalled, new PanelException('Plugin is already installed')); $this->pluginService->installPlugin($plugin); @@ -124,9 +120,7 @@ class PluginController extends ApplicationApiController */ public function update(WritePluginRequest $request, Plugin $plugin): array { - if (!$plugin->isUpdateAvailable()) { - throw new PanelException("Plugin doesn't need updating"); - } + throw_unless($plugin->isUpdateAvailable(), new PanelException("Plugin doesn't need updating")); $this->pluginService->updatePlugin($plugin); @@ -146,9 +140,7 @@ class PluginController extends ApplicationApiController */ public function uninstall(UninstallPluginRequest $request, Plugin $plugin): array { - if ($plugin->status === PluginStatus::NotInstalled) { - throw new PanelException('Plugin is not installed'); - } + throw_if($plugin->status === PluginStatus::NotInstalled, new PanelException('Plugin is not installed')); $this->pluginService->uninstallPlugin($plugin, $request->boolean('delete')); @@ -168,9 +160,7 @@ class PluginController extends ApplicationApiController */ public function enable(WritePluginRequest $request, Plugin $plugin): array { - if (!$plugin->canEnable()) { - throw new PanelException("Plugin can't be enabled"); - } + throw_unless($plugin->canEnable(), new PanelException("Plugin can't be enabled")); $this->pluginService->enablePlugin($plugin); @@ -190,9 +180,7 @@ class PluginController extends ApplicationApiController */ public function disable(WritePluginRequest $request, Plugin $plugin): array { - if (!$plugin->canDisable()) { - throw new PanelException("Plugin can't be disabled"); - } + throw_unless($plugin->canDisable(), new PanelException("Plugin can't be disabled")); $this->pluginService->disablePlugin($plugin); diff --git a/app/Http/Controllers/Api/Application/Roles/RoleController.php b/app/Http/Controllers/Api/Application/Roles/RoleController.php index 31cc97b40..076279d98 100644 --- a/app/Http/Controllers/Api/Application/Roles/RoleController.php +++ b/app/Http/Controllers/Api/Application/Roles/RoleController.php @@ -84,9 +84,7 @@ class RoleController extends ApplicationApiController */ public function update(UpdateRoleRequest $request, Role $role): array { - if ($role->isRootAdmin()) { - throw new PanelException('Can\'t update root admin role!'); - } + throw_if($role->isRootAdmin(), new PanelException('Can\'t update root admin role!')); $role->update($request->validated()); @@ -104,9 +102,7 @@ class RoleController extends ApplicationApiController */ public function delete(DeleteRoleRequest $request, Role $role): Response { - if ($role->isRootAdmin()) { - throw new PanelException('Can\'t delete root admin role!'); - } + throw_if($role->isRootAdmin(), new PanelException('Can\'t delete root admin role!')); $role->delete(); diff --git a/app/Http/Controllers/Api/Client/AccountController.php b/app/Http/Controllers/Api/Client/AccountController.php index 50a993e94..8b1ffa3a8 100644 --- a/app/Http/Controllers/Api/Client/AccountController.php +++ b/app/Http/Controllers/Api/Client/AccountController.php @@ -75,9 +75,7 @@ class AccountController extends ClientApiController // Only allow a user to change their email three times in the span // of 24 hours. This prevents malicious users from trying to find // existing accounts in the system by constantly changing their email. - if (RateLimiter::tooManyAttempts($key = "user:update-email:{$user->uuid}", 3)) { - throw new TooManyRequestsHttpException(message: 'Your email address has been changed too many times today. Please try again later.'); - } + throw_if(RateLimiter::tooManyAttempts($key = "user:update-email:{$user->uuid}", 3), new TooManyRequestsHttpException(message: 'Your email address has been changed too many times today. Please try again later.')); $original = $user->email; diff --git a/app/Http/Controllers/Api/Client/ApiKeyController.php b/app/Http/Controllers/Api/Client/ApiKeyController.php index 04e1a91e8..e6c738bb9 100644 --- a/app/Http/Controllers/Api/Client/ApiKeyController.php +++ b/app/Http/Controllers/Api/Client/ApiKeyController.php @@ -37,9 +37,7 @@ class ApiKeyController extends ClientApiController */ public function store(StoreApiKeyRequest $request): array { - if ($request->user()->apiKeys->count() >= config('panel.api.key_limit')) { - throw new DisplayException('You have reached the account limit for number of API keys.'); - } + throw_if($request->user()->apiKeys->count() >= config('panel.api.key_limit'), new DisplayException('You have reached the account limit for number of API keys.')); $token = $request->user()->createToken( $request->input('description'), diff --git a/app/Http/Controllers/Api/Client/Servers/BackupController.php b/app/Http/Controllers/Api/Client/Servers/BackupController.php index 2e8d28496..9419414f0 100644 --- a/app/Http/Controllers/Api/Client/Servers/BackupController.php +++ b/app/Http/Controllers/Api/Client/Servers/BackupController.php @@ -50,9 +50,7 @@ class BackupController extends ClientApiController */ public function index(Request $request, Server $server): array { - if (!$request->user()->can(SubuserPermission::BackupRead, $server)) { - throw new AuthorizationException(); - } + throw_unless($request->user()->can(SubuserPermission::BackupRead, $server), new AuthorizationException()); $limit = min($request->query('per_page') ?? 20, 50); @@ -118,9 +116,7 @@ class BackupController extends ClientApiController */ public function toggleLock(Request $request, Server $server, Backup $backup): array { - if (!$request->user()->can(SubuserPermission::BackupDelete, $server)) { - throw new AuthorizationException(); - } + throw_unless($request->user()->can(SubuserPermission::BackupDelete, $server), new AuthorizationException()); $action = $backup->is_locked ? 'server:backup.unlock' : 'server:backup.lock'; @@ -144,9 +140,7 @@ class BackupController extends ClientApiController */ public function view(Request $request, Server $server, Backup $backup): array { - if (!$request->user()->can(SubuserPermission::BackupRead, $server)) { - throw new AuthorizationException(); - } + throw_unless($request->user()->can(SubuserPermission::BackupRead, $server), new AuthorizationException()); return $this->fractal->item($backup) ->transformWith($this->getTransformer(BackupTransformer::class)) @@ -163,9 +157,7 @@ class BackupController extends ClientApiController */ public function delete(Request $request, Server $server, Backup $backup): JsonResponse { - if (!$request->user()->can(SubuserPermission::BackupDelete, $server)) { - throw new AuthorizationException(); - } + throw_unless($request->user()->can(SubuserPermission::BackupDelete, $server), new AuthorizationException()); $this->deleteBackupService->handle($backup); @@ -189,9 +181,7 @@ class BackupController extends ClientApiController */ public function download(Request $request, Server $server, Backup $backup): JsonResponse { - if (!$request->user()->can(SubuserPermission::BackupDownload, $server)) { - throw new AuthorizationException(); - } + throw_unless($request->user()->can(SubuserPermission::BackupDownload, $server), new AuthorizationException()); $schema = $this->backupService->get($backup->backupHost->schema); if (!$schema) { @@ -254,13 +244,9 @@ class BackupController extends ClientApiController { // Cannot restore a backup unless a server is fully installed and not currently // processing a different backup restoration request. - if (!is_null($server->status)) { - throw new BadRequestHttpException('This server is not currently in a state that allows for a backup to be restored.'); - } + throw_unless(is_null($server->status), new BadRequestHttpException('This server is not currently in a state that allows for a backup to be restored.')); - if (!$backup->is_successful && is_null($backup->completed_at)) { - throw new BadRequestHttpException('This backup cannot be restored at this time: not completed or failed.'); - } + throw_if(!$backup->is_successful && is_null($backup->completed_at), new BadRequestHttpException('This backup cannot be restored at this time: not completed or failed.')); $log = Activity::event('server:backup.restore') ->subject($backup) diff --git a/app/Http/Controllers/Api/Client/Servers/CommandController.php b/app/Http/Controllers/Api/Client/Servers/CommandController.php index 87490402e..e20f78248 100644 --- a/app/Http/Controllers/Api/Client/Servers/CommandController.php +++ b/app/Http/Controllers/Api/Client/Servers/CommandController.php @@ -31,9 +31,7 @@ class CommandController extends ClientApiController $previous = $exception->getPrevious(); if ($previous instanceof BadResponseException) { - if ($previous->getResponse()->getStatusCode() === Response::HTTP_BAD_GATEWAY) { - throw new HttpException(Response::HTTP_BAD_GATEWAY, 'Server must be online in order to send commands.', $exception); - } + throw_if($previous->getResponse()->getStatusCode() === Response::HTTP_BAD_GATEWAY, new HttpException(Response::HTTP_BAD_GATEWAY, 'Server must be online in order to send commands.', $exception)); } throw $exception; diff --git a/app/Http/Controllers/Api/Client/Servers/NetworkAllocationController.php b/app/Http/Controllers/Api/Client/Servers/NetworkAllocationController.php index fc8ae338d..8f43e0028 100644 --- a/app/Http/Controllers/Api/Client/Servers/NetworkAllocationController.php +++ b/app/Http/Controllers/Api/Client/Servers/NetworkAllocationController.php @@ -110,9 +110,7 @@ class NetworkAllocationController extends ClientApiController $allocation = Activity::event('server:allocation.create')->transaction(function ($log) use ($server) { $server->allocations()->lockForUpdate(); - if ($server->allocations->count() >= $server->allocation_limit) { - throw new DisplayException('Cannot assign additional allocations to this server: limit has been reached.'); - } + throw_if($server->allocations->count() >= $server->allocation_limit, new DisplayException('Cannot assign additional allocations to this server: limit has been reached.')); $allocation = $this->assignableAllocationService->handle($server); @@ -137,9 +135,7 @@ class NetworkAllocationController extends ClientApiController { // Don't allow the deletion of allocations if the server does not have an // allocation limit set. - if (empty($server->allocation_limit)) { - throw new DisplayException('You cannot delete allocations for this server: no allocation limit is set.'); - } + throw_if(empty($server->allocation_limit), new DisplayException('You cannot delete allocations for this server: no allocation limit is set.')); Allocation::query()->where('id', $allocation->id)->update([ 'notes' => null, diff --git a/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php b/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php index b9c3d8520..f731c7967 100644 --- a/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php +++ b/app/Http/Controllers/Api/Client/Servers/ResourceUtilizationController.php @@ -7,10 +7,10 @@ use App\Http\Requests\Api\Client\Servers\GetServerRequest; use App\Models\Server; use App\Repositories\Daemon\DaemonServerRepository; use App\Transformers\Api\Client\StatsTransformer; -use Carbon\Carbon; use Dedoc\Scramble\Attributes\Group; use Illuminate\Cache\Repository; use Illuminate\Http\Client\ConnectionException; +use Illuminate\Support\Carbon; #[Group('Server', weight: 3)] class ResourceUtilizationController extends ClientApiController diff --git a/app/Http/Controllers/Api/Client/Servers/ScheduleController.php b/app/Http/Controllers/Api/Client/Servers/ScheduleController.php index 9308d4ae3..2a270c60b 100644 --- a/app/Http/Controllers/Api/Client/Servers/ScheduleController.php +++ b/app/Http/Controllers/Api/Client/Servers/ScheduleController.php @@ -16,12 +16,12 @@ use App\Models\Schedule; use App\Models\Server; use App\Services\Schedules\ProcessScheduleService; use App\Transformers\Api\Client\ScheduleTransformer; -use Carbon\Carbon; use Dedoc\Scramble\Attributes\Group; use Exception; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Carbon; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Throwable; @@ -97,9 +97,7 @@ class ScheduleController extends ClientApiController */ public function view(ViewScheduleRequest $request, Server $server, Schedule $schedule): array { - if ($schedule->server_id !== $server->id) { - throw new NotFoundHttpException(); - } + throw_if($schedule->server_id !== $server->id, new NotFoundHttpException()); $schedule->loadMissing('tasks'); diff --git a/app/Http/Controllers/Api/Client/Servers/ScheduleTaskController.php b/app/Http/Controllers/Api/Client/Servers/ScheduleTaskController.php index ed817cc3b..085588343 100644 --- a/app/Http/Controllers/Api/Client/Servers/ScheduleTaskController.php +++ b/app/Http/Controllers/Api/Client/Servers/ScheduleTaskController.php @@ -46,13 +46,9 @@ class ScheduleTaskController extends ClientApiController public function store(StoreTaskRequest $request, Server $server, Schedule $schedule): array { $limit = config('panel.client_features.schedules.per_schedule_task_limit', 10); - if ($schedule->tasks()->count() >= $limit) { - throw new ServiceLimitExceededException("Schedules may not have more than $limit tasks associated with them. Creating this task would put this schedule over the limit."); - } + throw_if($schedule->tasks()->count() >= $limit, new ServiceLimitExceededException("Schedules may not have more than $limit tasks associated with them. Creating this task would put this schedule over the limit.")); - if ($server->backup_limit === 0 && $request->action === 'backup') { - throw new HttpForbiddenException("A backup task cannot be created when the server's backup limit is set to 0."); - } + throw_if($server->backup_limit === 0 && $request->action === 'backup', new HttpForbiddenException("A backup task cannot be created when the server's backup limit is set to 0.")); /** @var Task|null $lastTask */ $lastTask = $schedule->tasks()->orderByDesc('sequence_id')->first(); @@ -109,13 +105,9 @@ class ScheduleTaskController extends ClientApiController */ public function update(StoreTaskRequest $request, Server $server, Schedule $schedule, Task $task): array { - if ($schedule->id !== $task->schedule_id || $server->id !== $schedule->server_id) { - throw new NotFoundHttpException(); - } + throw_if($schedule->id !== $task->schedule_id || $server->id !== $schedule->server_id, new NotFoundHttpException()); - if ($server->backup_limit === 0 && $request->action === 'backup') { - throw new HttpForbiddenException("A backup task cannot be created when the server's backup limit is set to 0."); - } + throw_if($server->backup_limit === 0 && $request->action === 'backup', new HttpForbiddenException("A backup task cannot be created when the server's backup limit is set to 0.")); $this->connection->transaction(function () use ($request, $schedule, $task) { $sequenceId = $request->integer('sequence_id', $task->sequence_id); @@ -166,13 +158,9 @@ class ScheduleTaskController extends ClientApiController */ public function delete(ClientApiRequest $request, Server $server, Schedule $schedule, Task $task): JsonResponse { - if ($task->schedule_id !== $schedule->id || $schedule->server_id !== $server->id) { - throw new NotFoundHttpException(); - } + throw_if($task->schedule_id !== $schedule->id || $schedule->server_id !== $server->id, new NotFoundHttpException()); - if (!$request->user()->can(SubuserPermission::ScheduleDelete, $server)) { - throw new HttpForbiddenException('You do not have permission to perform this action.'); - } + throw_unless($request->user()->can(SubuserPermission::ScheduleDelete, $server), new HttpForbiddenException('You do not have permission to perform this action.')); $schedule->tasks() ->where('sequence_id', '>', $task->sequence_id) diff --git a/app/Http/Controllers/Api/Client/Servers/SettingsController.php b/app/Http/Controllers/Api/Client/Servers/SettingsController.php index 8b60e8935..ec93a1596 100644 --- a/app/Http/Controllers/Api/Client/Servers/SettingsController.php +++ b/app/Http/Controllers/Api/Client/Servers/SettingsController.php @@ -96,9 +96,7 @@ class SettingsController extends ClientApiController */ public function dockerImage(SetDockerImageRequest $request, Server $server): JsonResponse { - if (!in_array($server->image, $server->egg->docker_images)) { - throw new BadRequestHttpException('This server\'s Docker image has been manually set by an administrator and cannot be updated.'); - } + throw_unless(in_array($server->image, $server->egg->docker_images), new BadRequestHttpException('This server\'s Docker image has been manually set by an administrator and cannot be updated.')); $original = $server->image; $server->forceFill(['image' => $request->input('docker_image')])->saveOrFail(); diff --git a/app/Http/Controllers/Api/Client/Servers/StartupController.php b/app/Http/Controllers/Api/Client/Servers/StartupController.php index 8ee9a9d24..89e59d713 100644 --- a/app/Http/Controllers/Api/Client/Servers/StartupController.php +++ b/app/Http/Controllers/Api/Client/Servers/StartupController.php @@ -64,11 +64,9 @@ class StartupController extends ClientApiController { $variable = $server->variables()->where('env_variable', $request->input('key'))->first(); - if (!$variable || !$variable->user_viewable) { - throw new BadRequestHttpException('The environment variable you are trying to edit does not exist.'); - } elseif (!$variable->user_editable) { - throw new BadRequestHttpException('The environment variable you are trying to edit is read-only.'); - } + throw_if(!$variable || !$variable->user_viewable, new BadRequestHttpException('The environment variable you are trying to edit does not exist.')); + + throw_unless($variable->user_editable, new BadRequestHttpException('The environment variable you are trying to edit is read-only.')); $original = $variable->server_value; diff --git a/app/Http/Controllers/Api/Client/Servers/WebsocketController.php b/app/Http/Controllers/Api/Client/Servers/WebsocketController.php index 3dbd86267..e63c424ec 100644 --- a/app/Http/Controllers/Api/Client/Servers/WebsocketController.php +++ b/app/Http/Controllers/Api/Client/Servers/WebsocketController.php @@ -38,18 +38,14 @@ class WebsocketController extends ClientApiController public function __invoke(ClientApiRequest $request, Server $server): JsonResponse { $user = $request->user(); - if ($user->cannot(SubuserPermission::WebsocketConnect, $server)) { - throw new HttpForbiddenException('You do not have permission to connect to this server\'s websocket.'); - } + throw_if($user->cannot(SubuserPermission::WebsocketConnect, $server), new HttpForbiddenException('You do not have permission to connect to this server\'s websocket.')); $permissions = $this->permissionsService->handle($server, $user); $node = $server->node; if (!is_null($server->transfer)) { // Check if the user has permissions to receive transfer logs. - if (!in_array('admin.websocket.transfer', $permissions)) { - throw new HttpForbiddenException('You do not have permission to view server transfer logs.'); - } + throw_unless(in_array('admin.websocket.transfer', $permissions), new HttpForbiddenException('You do not have permission to view server transfer logs.')); // Redirect the websocket request to the new node if the server has been archived. if ($server->transfer->archived) { diff --git a/app/Http/Controllers/Api/Remote/ActivityProcessingController.php b/app/Http/Controllers/Api/Remote/ActivityProcessingController.php index 631a625f1..4f06ee632 100644 --- a/app/Http/Controllers/Api/Remote/ActivityProcessingController.php +++ b/app/Http/Controllers/Api/Remote/ActivityProcessingController.php @@ -9,9 +9,9 @@ use App\Models\ActivityLog; use App\Models\Node; use App\Models\Server; use App\Models\User; -use Carbon\Carbon; use DateTimeInterface; use Exception; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Event; use Illuminate\Support\Str; diff --git a/app/Http/Controllers/Api/Remote/Backups/BackupRemoteUploadController.php b/app/Http/Controllers/Api/Remote/Backups/BackupRemoteUploadController.php index 6c2e4f875..e67295618 100644 --- a/app/Http/Controllers/Api/Remote/Backups/BackupRemoteUploadController.php +++ b/app/Http/Controllers/Api/Remote/Backups/BackupRemoteUploadController.php @@ -37,9 +37,7 @@ class BackupRemoteUploadController extends Controller $node = $request->attributes->get('node'); $size = (int) $request->query('size'); - if (empty($size)) { - throw new BadRequestHttpException('A non-empty "size" query parameter must be provided.'); - } + throw_if(empty($size), new BadRequestHttpException('A non-empty "size" query parameter must be provided.')); $backup = Backup::where('uuid', $backup)->firstOrFail(); diff --git a/app/Http/Controllers/Api/Remote/Backups/BackupStatusController.php b/app/Http/Controllers/Api/Remote/Backups/BackupStatusController.php index a24dda96e..2d9d20399 100644 --- a/app/Http/Controllers/Api/Remote/Backups/BackupStatusController.php +++ b/app/Http/Controllers/Api/Remote/Backups/BackupStatusController.php @@ -45,13 +45,9 @@ class BackupStatusController extends Controller // from messing with backups that they don't own. /** @var Server $server */ $server = $model->server; - if ($server->node_id !== $node->id) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_if($server->node_id !== $node->id, new HttpForbiddenException('Requesting node does not have permission to access this server.')); - if ($model->is_successful) { - throw new BadRequestHttpException('Cannot update the status of a backup that is already marked as completed.'); - } + throw_if($model->is_successful, new BadRequestHttpException('Cannot update the status of a backup that is already marked as completed.')); $action = $request->boolean('successful') ? 'server:backup.complete' : 'server:backup.fail'; $log = Activity::event($action)->subject($model, $model->server)->property('name', $model->name); @@ -99,9 +95,7 @@ class BackupStatusController extends Controller $model = Backup::query()->where('uuid', $backup)->firstOrFail(); $node = $request->attributes->get('node'); - if (!$model->server->node->is($node)) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_unless($model->server->node->is($node), new HttpForbiddenException('Requesting node does not have permission to access this server.')); $model->server->update(['status' => null]); diff --git a/app/Http/Controllers/Api/Remote/Servers/ServerContainersController.php b/app/Http/Controllers/Api/Remote/Servers/ServerContainersController.php index 424733240..d7e8b5efa 100644 --- a/app/Http/Controllers/Api/Remote/Servers/ServerContainersController.php +++ b/app/Http/Controllers/Api/Remote/Servers/ServerContainersController.php @@ -16,9 +16,7 @@ class ServerContainersController extends Controller */ public function status(Request $request, Server $server): JsonResponse { - if (!$server->node->is($request->attributes->get('node'))) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_unless($server->node->is($request->attributes->get('node')), new HttpForbiddenException('Requesting node does not have permission to access this server.')); $status = ContainerStatus::tryFrom($request->json('data.new_state')) ?? ContainerStatus::Missing; diff --git a/app/Http/Controllers/Api/Remote/Servers/ServerDetailsController.php b/app/Http/Controllers/Api/Remote/Servers/ServerDetailsController.php index 7c53af6ee..3fee758dd 100644 --- a/app/Http/Controllers/Api/Remote/Servers/ServerDetailsController.php +++ b/app/Http/Controllers/Api/Remote/Servers/ServerDetailsController.php @@ -45,9 +45,7 @@ class ServerDetailsController extends Controller // to fetch these details. $valid = $transfer ? $node->id === $transfer->old_node || $node->id === $transfer->new_node : $node->id === $server->node_id; - if (!$valid) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_unless($valid, new HttpForbiddenException('Requesting node does not have permission to access this server.')); return new JsonResponse([ 'settings' => $this->configurationStructureService->handle($server), diff --git a/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php b/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php index bedf6adc6..37e4cfc3e 100644 --- a/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php +++ b/app/Http/Controllers/Api/Remote/Servers/ServerInstallController.php @@ -20,9 +20,7 @@ class ServerInstallController extends Controller */ public function index(Request $request, Server $server): JsonResponse { - if (!$server->node->is($request->attributes->get('node'))) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_unless($server->node->is($request->attributes->get('node')), new HttpForbiddenException('Requesting node does not have permission to access this server.')); $egg = $server->egg; @@ -42,9 +40,7 @@ class ServerInstallController extends Controller { $status = null; - if (!$server->node->is($request->attributes->get('node'))) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_unless($server->node->is($request->attributes->get('node')), new HttpForbiddenException('Requesting node does not have permission to access this server.')); $successful = $request->boolean('successful'); diff --git a/app/Http/Controllers/Api/Remote/Servers/ServerTransferController.php b/app/Http/Controllers/Api/Remote/Servers/ServerTransferController.php index f3db17c50..d6be75a6a 100644 --- a/app/Http/Controllers/Api/Remote/Servers/ServerTransferController.php +++ b/app/Http/Controllers/Api/Remote/Servers/ServerTransferController.php @@ -35,18 +35,14 @@ class ServerTransferController extends Controller public function failure(Request $request, Server $server): JsonResponse { $transfer = $server->transfer; - if (is_null($transfer)) { - throw new ConflictHttpException('Server is not being transferred.'); - } + throw_if(is_null($transfer), new ConflictHttpException('Server is not being transferred.')); /* @var Node $node */ Assert::isInstanceOf($node = $request->attributes->get('node'), Node::class); // Either node can tell the panel that the transfer has failed. Only the new node // can tell the panel that it was successful. - if (!$node->is($transfer->newNode) && !$node->is($transfer->oldNode)) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_if(!$node->is($transfer->newNode) && !$node->is($transfer->oldNode), new HttpForbiddenException('Requesting node does not have permission to access this server.')); $this->connection->transaction(function () use ($transfer) { $transfer->forceFill(['successful' => false])->saveOrFail(); @@ -68,18 +64,14 @@ class ServerTransferController extends Controller public function success(Request $request, Server $server): JsonResponse { $transfer = $server->transfer; - if (is_null($transfer)) { - throw new ConflictHttpException('Server is not being transferred.'); - } + throw_if(is_null($transfer), new ConflictHttpException('Server is not being transferred.')); /* @var Node $node */ Assert::isInstanceOf($node = $request->attributes->get('node'), Node::class); // Only the new node communicates a successful state to the panel, so we should // not allow the old node to hit this endpoint. - if (!$node->is($transfer->newNode)) { - throw new HttpForbiddenException('Requesting node does not have permission to access this server.'); - } + throw_unless($node->is($transfer->newNode), new HttpForbiddenException('Requesting node does not have permission to access this server.')); /** @var Server $server */ $server = $this->connection->transaction(function () use ($server, $transfer) { diff --git a/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php b/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php index a0c39c508..a8ae58ff6 100644 --- a/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php +++ b/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php @@ -32,9 +32,7 @@ class SftpAuthenticationController extends Controller public function __invoke(SftpAuthenticationFormRequest $request): JsonResponse { $connection = $this->parseUsername($request->input('username')); - if (empty($connection['server'])) { - throw new BadRequestHttpException('No valid server identifier was included in the request.'); - } + throw_if(empty($connection['server']), new BadRequestHttpException('No valid server identifier was included in the request.')); if ($this->hasTooManyLoginAttempts($request)) { $seconds = $this->limiter()->availableIn($this->throttleKey($request)); diff --git a/app/Http/Middleware/Api/Application/AuthenticateApplicationUser.php b/app/Http/Middleware/Api/Application/AuthenticateApplicationUser.php index c53807afc..470e71ffd 100644 --- a/app/Http/Middleware/Api/Application/AuthenticateApplicationUser.php +++ b/app/Http/Middleware/Api/Application/AuthenticateApplicationUser.php @@ -17,9 +17,7 @@ class AuthenticateApplicationUser { /** @var User|null $user */ $user = $request->user(); - if (!$user || !$user->isAdmin()) { - throw new AccessDeniedHttpException('This account does not have permission to access the API.'); - } + throw_if(!$user || !$user->isAdmin(), new AccessDeniedHttpException('This account does not have permission to access the API.')); return $next($request); } diff --git a/app/Http/Middleware/Api/Client/RequireClientApiKey.php b/app/Http/Middleware/Api/Client/RequireClientApiKey.php index 63a92e95e..16fac58eb 100644 --- a/app/Http/Middleware/Api/Client/RequireClientApiKey.php +++ b/app/Http/Middleware/Api/Client/RequireClientApiKey.php @@ -17,9 +17,7 @@ class RequireClientApiKey { $token = $request->user()->currentAccessToken(); - if ($token instanceof ApiKey && $token->key_type === ApiKey::TYPE_APPLICATION) { - throw new AccessDeniedHttpException('You are attempting to use an application API key on an endpoint that requires a client API key.'); - } + throw_if($token instanceof ApiKey && $token->key_type === ApiKey::TYPE_APPLICATION, new AccessDeniedHttpException('You are attempting to use an application API key on an endpoint that requires a client API key.')); return $next($request); } diff --git a/app/Http/Middleware/Api/Client/Server/AuthenticateServerAccess.php b/app/Http/Middleware/Api/Client/Server/AuthenticateServerAccess.php index bfdb24a8d..408ccb67a 100644 --- a/app/Http/Middleware/Api/Client/Server/AuthenticateServerAccess.php +++ b/app/Http/Middleware/Api/Client/Server/AuthenticateServerAccess.php @@ -34,18 +34,14 @@ class AuthenticateServerAccess $user = $request->user(); $server = $request->route()->parameter('server'); - if (!$server instanceof Server) { - throw new NotFoundHttpException(trans('exceptions.api.resource_not_found')); - } + throw_unless($server instanceof Server, new NotFoundHttpException(trans('exceptions.api.resource_not_found'))); // At the very least, ensure that the user trying to make this request is the // server owner, a subuser, or an admin. We'll leave it up to the controllers // to authenticate more detailed permissions if needed. if ($user->id !== $server->owner_id && $user->cannot('update server', $server)) { // Check for subuser status. - if (!$server->subusers->contains('user_id', $user->id)) { - throw new NotFoundHttpException(trans('exceptions.api.resource_not_found')); - } + throw_unless($server->subusers->contains('user_id', $user->id), new NotFoundHttpException(trans('exceptions.api.resource_not_found'))); } try { @@ -54,12 +50,8 @@ class AuthenticateServerAccess // Still allow users to get information about their server if it is installing or // being transferred. if (!$request->routeIs('api:client:server.view')) { - if (($server->isSuspended() || $server->node->isUnderMaintenance()) && !$request->routeIs('api:client:server.resources')) { - throw $exception; - } - if ($user->cannot('update server', $server) || !$request->routeIs($this->except)) { - throw $exception; - } + throw_if(($server->isSuspended() || $server->node->isUnderMaintenance()) && !$request->routeIs('api:client:server.resources'), $exception); + throw_if($user->cannot('update server', $server) || !$request->routeIs($this->except), $exception); } } diff --git a/app/Http/Middleware/Api/Client/Server/ResourceBelongsToServer.php b/app/Http/Middleware/Api/Client/Server/ResourceBelongsToServer.php index 7b3073920..5945505ea 100644 --- a/app/Http/Middleware/Api/Client/Server/ResourceBelongsToServer.php +++ b/app/Http/Middleware/Api/Client/Server/ResourceBelongsToServer.php @@ -31,9 +31,7 @@ class ResourceBelongsToServer $params = $request->route()->parameters(); $server = $params['server'] ?? null; - if (!$server instanceof Server) { - throw new InvalidArgumentException('This middleware cannot be used in a context that is missing a server in the parameters.'); - } + throw_unless($server instanceof Server, new InvalidArgumentException('This middleware cannot be used in a context that is missing a server in the parameters.')); /** @var Server $server */ $server = $request->route()->parameter('server'); @@ -55,17 +53,13 @@ class ResourceBelongsToServer case Database::class: case Schedule::class: case Subuser::class: - if ($model->server_id !== $server->id) { - throw $exception; - } + throw_if($model->server_id !== $server->id, $exception); break; // Regular users are a special case here as we need to make sure they're // currently assigned as a subuser on the server. case User::class: $subuser = $server->subusers()->where('user_id', $model->id)->first(); - if (is_null($subuser)) { - throw $exception; - } + throw_if(is_null($subuser), $exception); // This is a special case to avoid an additional query being triggered // in the underlying logic. $request->attributes->set('subuser', $subuser); @@ -75,9 +69,7 @@ class ResourceBelongsToServer case Task::class: /** @var Schedule $schedule */ $schedule = $request->route()->parameter('schedule'); - if ($model->schedule_id !== $schedule->id || $schedule->server_id !== $server->id) { - throw $exception; - } + throw_if($model->schedule_id !== $schedule->id || $schedule->server_id !== $server->id, $exception); break; default: // Don't return a 404 here since we want to make sure no one relies diff --git a/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php b/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php index a9fd6c646..e69bb286b 100644 --- a/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php +++ b/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php @@ -31,15 +31,11 @@ class DaemonAuthenticate return $next($request); } - if (is_null($bearer = $request->bearerToken())) { - throw new HttpException(401, 'Access to this endpoint must include an Authorization header.', null, ['WWW-Authenticate' => 'Bearer']); - } + throw_if(is_null($bearer = $request->bearerToken()), new HttpException(401, 'Access to this endpoint must include an Authorization header.', null, ['WWW-Authenticate' => 'Bearer'])); $parts = explode('.', $bearer); // Ensure that all the correct parts are provided in the header. - if (count($parts) !== 2 || empty($parts[0]) || empty($parts[1])) { - throw new BadRequestHttpException('The Authorization header provided was not in a valid format.'); - } + throw_if(count($parts) !== 2 || empty($parts[0]) || empty($parts[1]), new BadRequestHttpException('The Authorization header provided was not in a valid format.')); /** @var Node $node */ $node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail(); diff --git a/app/Http/Middleware/RequireTwoFactorAuthentication.php b/app/Http/Middleware/RequireTwoFactorAuthentication.php index e486b0e90..cdcce878f 100644 --- a/app/Http/Middleware/RequireTwoFactorAuthentication.php +++ b/app/Http/Middleware/RequireTwoFactorAuthentication.php @@ -49,9 +49,7 @@ class RequireTwoFactorAuthentication } // For API calls return an exception which gets rendered nicely in the API response... - if ($request->isJson() || Str::startsWith($request->path(), '/api')) { - throw new TwoFactorAuthRequiredException(); - } + throw_if($request->isJson() || Str::startsWith($request->path(), '/api'), new TwoFactorAuthRequiredException()); // ... otherwise display banner and redirect to profile AlertBanner::make('2fa_must_be_enabled') diff --git a/app/Http/Requests/Api/Application/ApplicationApiRequest.php b/app/Http/Requests/Api/Application/ApplicationApiRequest.php index f72f33c99..83342e8cb 100644 --- a/app/Http/Requests/Api/Application/ApplicationApiRequest.php +++ b/app/Http/Requests/Api/Application/ApplicationApiRequest.php @@ -33,9 +33,7 @@ abstract class ApplicationApiRequest extends FormRequest */ public function authorize(): bool { - if (is_null($this->resource)) { - throw new PanelException('An ACL resource must be defined on API requests.'); - } + throw_if(is_null($this->resource), new PanelException('An ACL resource must be defined on API requests.')); /** @var TransientToken|ApiKey $token */ $token = $this->user()->currentAccessToken(); diff --git a/app/Http/Requests/Api/Client/Account/StoreSSHKeyRequest.php b/app/Http/Requests/Api/Client/Account/StoreSSHKeyRequest.php index fa7766315..5853cd2a9 100644 --- a/app/Http/Requests/Api/Client/Account/StoreSSHKeyRequest.php +++ b/app/Http/Requests/Api/Client/Account/StoreSSHKeyRequest.php @@ -68,9 +68,7 @@ class StoreSSHKeyRequest extends ClientApiRequest */ public function getKeyFingerprint(): string { - if (!$this->key) { - throw new Exception('The public key was not properly loaded for this request.'); - } + throw_unless($this->key, new Exception('The public key was not properly loaded for this request.')); return $this->key->getFingerprint('sha256'); } diff --git a/app/Http/Requests/Api/Client/Account/UpdateEmailRequest.php b/app/Http/Requests/Api/Client/Account/UpdateEmailRequest.php index 68bdb31d7..21abf8f79 100644 --- a/app/Http/Requests/Api/Client/Account/UpdateEmailRequest.php +++ b/app/Http/Requests/Api/Client/Account/UpdateEmailRequest.php @@ -22,9 +22,7 @@ class UpdateEmailRequest extends ClientApiRequest $hasher = Container::getInstance()->make(Hasher::class); // Verify password matches when changing password or email. - if (!$hasher->check($this->input('password'), $this->user()->password)) { - throw new InvalidPasswordProvidedException(trans('validation.internal.invalid_password')); - } + throw_unless($hasher->check($this->input('password'), $this->user()->password), new InvalidPasswordProvidedException(trans('validation.internal.invalid_password'))); return !$this->user()->is_managed_externally; } diff --git a/app/Http/Requests/Api/Client/Account/UpdatePasswordRequest.php b/app/Http/Requests/Api/Client/Account/UpdatePasswordRequest.php index afbbc1f2f..ecb29af21 100644 --- a/app/Http/Requests/Api/Client/Account/UpdatePasswordRequest.php +++ b/app/Http/Requests/Api/Client/Account/UpdatePasswordRequest.php @@ -21,9 +21,7 @@ class UpdatePasswordRequest extends ClientApiRequest $hasher = Container::getInstance()->make(Hasher::class); // Verify password matches when changing password or email. - if (!$hasher->check($this->input('current_password'), $this->user()->password)) { - throw new InvalidPasswordProvidedException(trans('validation.internal.invalid_password')); - } + throw_unless($hasher->check($this->input('current_password'), $this->user()->password), new InvalidPasswordProvidedException(trans('validation.internal.invalid_password'))); return !$this->user()->is_managed_externally; } diff --git a/app/Http/Requests/Api/Client/Account/UpdateUsernameRequest.php b/app/Http/Requests/Api/Client/Account/UpdateUsernameRequest.php index ac2ba0b59..e0fc16466 100644 --- a/app/Http/Requests/Api/Client/Account/UpdateUsernameRequest.php +++ b/app/Http/Requests/Api/Client/Account/UpdateUsernameRequest.php @@ -22,9 +22,7 @@ class UpdateUsernameRequest extends ClientApiRequest $hasher = Container::getInstance()->make(Hasher::class); // Verify password matches when changing password or email. - if (!$hasher->check($this->input('password'), $this->user()->password)) { - throw new InvalidPasswordProvidedException(trans('validation.internal.invalid_password')); - } + throw_unless($hasher->check($this->input('password'), $this->user()->password), new InvalidPasswordProvidedException(trans('validation.internal.invalid_password'))); return !$this->user()->is_managed_externally; } diff --git a/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php b/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php index ae8264dd2..293252a08 100644 --- a/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php @@ -28,9 +28,7 @@ class ViewScheduleRequest extends ClientApiRequest if ($server instanceof Server && $schedule instanceof Schedule) { $task = $this->route()->parameter('task'); - if ($schedule->server_id !== $server->id || ($task instanceof Task && $task->schedule_id !== $schedule->id)) { - throw new NotFoundHttpException('The requested resource does not exist on the system.'); - } + throw_if($schedule->server_id !== $server->id || ($task instanceof Task && $task->schedule_id !== $schedule->id), new NotFoundHttpException('The requested resource does not exist on the system.')); } return true; diff --git a/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php b/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php index 1a5d21274..47340f949 100644 --- a/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Subusers/SubuserRequest.php @@ -70,8 +70,6 @@ abstract class SubuserRequest extends ClientApiRequest /** @var GetUserPermissionsService $service */ $service = $this->container->make(GetUserPermissionsService::class); - if (count(array_diff($permissions, $service->handle($server, $user))) > 0) { - throw new HttpForbiddenException('Cannot assign permissions to a subuser that your account does not actively possess.'); - } + throw_if(count(array_diff($permissions, $service->handle($server, $user))) > 0, new HttpForbiddenException('Cannot assign permissions to a subuser that your account does not actively possess.')); } } diff --git a/app/Jobs/Schedule/RunTaskJob.php b/app/Jobs/Schedule/RunTaskJob.php index 56d1a4756..e3909c3ee 100644 --- a/app/Jobs/Schedule/RunTaskJob.php +++ b/app/Jobs/Schedule/RunTaskJob.php @@ -56,17 +56,13 @@ class RunTaskJob implements ShouldQueue try { $taskSchema = $taskService->get($this->task->action); - if (!$taskSchema) { - throw new InvalidArgumentException('Invalid task action provided: ' . $this->task->action); - } + throw_unless($taskSchema, new InvalidArgumentException('Invalid task action provided: ' . $this->task->action)); $taskSchema->runTask($this->task); } catch (Exception $exception) { // If this isn't a ConnectionException on a task that allows for failures // throw the exception back up the chain so that the task is stopped. - if (!($this->task->continue_on_failure && $exception instanceof ConnectionException)) { - throw $exception; - } + throw_unless(($this->task->continue_on_failure && $exception instanceof ConnectionException), $exception); } $this->markTaskNotQueued(); @@ -89,7 +85,7 @@ class RunTaskJob implements ShouldQueue { /** @var Task|null $nextTask */ $nextTask = Task::query()->where('schedule_id', $this->task->schedule_id) - ->orderBy('sequence_id', 'asc') + ->orderBy('sequence_id') ->where('sequence_id', '>', $this->task->sequence_id) ->first(); diff --git a/app/Livewire/Installer/Steps/CacheStep.php b/app/Livewire/Installer/Steps/CacheStep.php index 0e0c5239f..cb512cc34 100644 --- a/app/Livewire/Installer/Steps/CacheStep.php +++ b/app/Livewire/Installer/Steps/CacheStep.php @@ -79,9 +79,7 @@ class CacheStep ->afterValidation(function (Get $get, Application $app) use ($installer) { $driver = $get('env_cache.CACHE_STORE'); - if (!self::testConnection($app, $driver, $get('env_cache.REDIS_HOST'), $get('env_cache.REDIS_PORT'), $get('env_cache.REDIS_USERNAME'), $get('env_cache.REDIS_PASSWORD'))) { - throw new Halt('Redis connection failed'); - } + throw_unless(self::testConnection($app, $driver, $get('env_cache.REDIS_HOST'), $get('env_cache.REDIS_PORT'), $get('env_cache.REDIS_USERNAME'), $get('env_cache.REDIS_PASSWORD')), new Halt('Redis connection failed')); $installer->writeToEnv('env_cache'); }); diff --git a/app/Livewire/Installer/Steps/DatabaseStep.php b/app/Livewire/Installer/Steps/DatabaseStep.php index ef5606ab9..eaeb16f07 100644 --- a/app/Livewire/Installer/Steps/DatabaseStep.php +++ b/app/Livewire/Installer/Steps/DatabaseStep.php @@ -97,9 +97,7 @@ class DatabaseStep ->afterValidation(function (Get $get) use ($installer) { $driver = $get('env_database.DB_CONNECTION'); - if (!self::testConnection($driver, $get('env_database.DB_HOST'), $get('env_database.DB_PORT'), $get('env_database.DB_DATABASE'), $get('env_database.DB_USERNAME'), $get('env_database.DB_PASSWORD'))) { - throw new Halt(trans('installer.database.exceptions.connection')); - } + throw_unless(self::testConnection($driver, $get('env_database.DB_HOST'), $get('env_database.DB_PORT'), $get('env_database.DB_DATABASE'), $get('env_database.DB_USERNAME'), $get('env_database.DB_PASSWORD')), new Halt(trans('installer.database.exceptions.connection'))); $installer->writeToEnv('env_database'); }); diff --git a/app/Models/ActivityLog.php b/app/Models/ActivityLog.php index b5a250f83..7ace15761 100644 --- a/app/Models/ActivityLog.php +++ b/app/Models/ActivityLog.php @@ -123,9 +123,7 @@ class ActivityLog extends Model implements HasIcon, HasLabel public function prunable(): Builder { - if (is_null(config('activity.prune_days'))) { - throw new LogicException('Cannot prune activity logs: no "prune_days" configuration value is set.'); - } + throw_if(is_null(config('activity.prune_days')), new LogicException('Cannot prune activity logs: no "prune_days" configuration value is set.')); return static::where('timestamp', '<=', Carbon::now()->subDays(config('activity.prune_days'))); } diff --git a/app/Models/Filters/MultiFieldServerFilter.php b/app/Models/Filters/MultiFieldServerFilter.php index 33d7eb58d..cef413fae 100644 --- a/app/Models/Filters/MultiFieldServerFilter.php +++ b/app/Models/Filters/MultiFieldServerFilter.php @@ -28,9 +28,7 @@ class MultiFieldServerFilter implements Filter */ public function __invoke(Builder $query, $value, string $property): void { - if ($query->getQuery()->from !== 'servers') { - throw new BadMethodCallException('Cannot use the MultiFieldServerFilter against a non-server model.'); - } + throw_if($query->getQuery()->from !== 'servers', new BadMethodCallException('Cannot use the MultiFieldServerFilter against a non-server model.')); if (preg_match(self::IPV4_REGEX, $value) || preg_match('/^:\d{1,5}$/', $value)) { $query diff --git a/app/Models/Plugin.php b/app/Models/Plugin.php index fa4199e04..9fb15d395 100644 --- a/app/Models/Plugin.php +++ b/app/Models/Plugin.php @@ -133,9 +133,7 @@ class Plugin extends Model implements HasPluginSettings $data = File::json($path, JSON_THROW_ON_ERROR); $data['id'] = Str::lower($data['id']); - if ($data['id'] !== Str::lower($plugin)) { - throw new PluginIdMismatchException("Plugin id mismatch for folder name ($plugin) and id in plugin.json ({$data['id']})!"); - } + throw_if($data['id'] !== Str::lower($plugin), new PluginIdMismatchException("Plugin id mismatch for folder name ($plugin) and id in plugin.json ({$data['id']})!")); $panels = null; if (array_key_exists('panels', $data)) { @@ -171,9 +169,7 @@ class Plugin extends Model implements HasPluginSettings $plugins[] = $data; } catch (Exception $exception) { - if (config('panel.plugin.dev_mode', false)) { - throw ($exception); - } + throw_if(config('panel.plugin.dev_mode', false), ($exception)); report($exception); diff --git a/app/Models/Server.php b/app/Models/Server.php index 0909cdd09..c202b10b2 100644 --- a/app/Models/Server.php +++ b/app/Models/Server.php @@ -429,9 +429,7 @@ class Server extends Model implements HasAvatar, Validatable */ public function validateCurrentState(): void { - if ($this->isInConflictState()) { - throw new ServerStateConflictException($this); - } + throw_if($this->isInConflictState(), new ServerStateConflictException($this)); } /** @@ -442,11 +440,9 @@ class Server extends Model implements HasAvatar, Validatable */ public function validateTransferState(): void { - if ( - !$this->isInstalled() || + if (!$this->isInstalled() || $this->status === ServerState::RestoringBackup || - !is_null($this->transfer) - ) { + !is_null($this->transfer)) { throw new ServerStateConflictException($this); } } diff --git a/app/Models/Traits/HasIcon.php b/app/Models/Traits/HasIcon.php index b8693d081..6e404da99 100644 --- a/app/Models/Traits/HasIcon.php +++ b/app/Models/Traits/HasIcon.php @@ -48,15 +48,11 @@ trait HasIcon default => null, }; - if (is_null($normalizedExtension)) { - throw new Exception(trans('admin/egg.import.unknown_extension', ['extension' => $extension])); - } + throw_if(is_null($normalizedExtension), new Exception(trans('admin/egg.import.unknown_extension', ['extension' => $extension]))); $fileName = static::getIconStoragePath() . "/$this->uuid.$normalizedExtension"; - if (!Storage::disk('public')->put($fileName, $data)) { - throw new Exception(trans('admin/egg.import.could_not_write')); - } + throw_unless(Storage::disk('public')->put($fileName, $data), new Exception(trans('admin/egg.import.could_not_write'))); foreach (['png', 'jpg', 'jpeg', 'webp', 'svg'] as $ext) { if ($ext === $normalizedExtension) { diff --git a/app/Models/WebhookConfiguration.php b/app/Models/WebhookConfiguration.php index ff3012ebc..ad2e4d957 100644 --- a/app/Models/WebhookConfiguration.php +++ b/app/Models/WebhookConfiguration.php @@ -317,7 +317,7 @@ class WebhookConfiguration extends Model $serverEvents = collect(static::discoverCustomEvents()) ->merge(static::allModelEvents()) ->unique() - ->filter(fn ($event) => str($event)->contains('App\\Models\\Server') && !str($event)->contains('Subuser')) + ->filter(fn ($event) => str($event)->contains(Server::class) && !str($event)->contains('Subuser')) ->values() ->all(); diff --git a/app/Repositories/Daemon/DaemonFileRepository.php b/app/Repositories/Daemon/DaemonFileRepository.php index 15e52fcdb..633881cc6 100644 --- a/app/Repositories/Daemon/DaemonFileRepository.php +++ b/app/Repositories/Daemon/DaemonFileRepository.php @@ -30,21 +30,15 @@ class DaemonFileRepository extends DaemonRepository } catch (RequestException $exception) { $status = $exception->response->status(); - if ($status === 400) { - throw new FileNotEditableException(); - } + throw_if($status === 400, new FileNotEditableException()); - if ($status === 404) { - throw new FileNotFoundException(); - } + throw_if($status === 404, new FileNotFoundException()); throw $exception; } $length = $response->header('Content-Length'); - if ($notLargerThan && $length > $notLargerThan) { - throw new FileSizeTooLargeException(); - } + throw_if($notLargerThan && $length > $notLargerThan, new FileSizeTooLargeException()); return $response; } @@ -64,9 +58,7 @@ class DaemonFileRepository extends DaemonRepository ->withBody($content) ->post("/api/servers/{$this->server->uuid}/files/write"); } catch (RequestException $exception) { - if ($exception->response->status() === 400) { - throw new FileExistsException(); - } + throw_if($exception->response->status() === 400, new FileExistsException()); throw $exception; } @@ -102,9 +94,7 @@ class DaemonFileRepository extends DaemonRepository ] ); } catch (RequestException $exception) { - if ($exception->response->status() === 400) { - throw new FileExistsException(); - } + throw_if($exception->response->status() === 400, new FileExistsException()); throw $exception; } diff --git a/app/Repositories/Daemon/DaemonRepository.php b/app/Repositories/Daemon/DaemonRepository.php index 18bfdbafe..6b14f1ed3 100644 --- a/app/Repositories/Daemon/DaemonRepository.php +++ b/app/Repositories/Daemon/DaemonRepository.php @@ -59,13 +59,9 @@ abstract class DaemonRepository } $header = $condition->header('User-Agent'); - if ( - empty($header) || + throw_if(empty($header) || preg_match('/^Pelican Wings\/v(?:\d+\.\d+\.\d+|develop) \(id:(\w*)\)$/', $header, $matches) && - array_get($matches, 1, '') !== $this->node->daemon_token_id - ) { - throw new ConnectionException($condition->effectiveUri()->__toString() . ' does not match node token_id !'); - } + array_get($matches, 1, '') !== $this->node->daemon_token_id, new ConnectionException($condition->effectiveUri()->__toString() . ' does not match node token_id !')); return true; } diff --git a/app/Repositories/Daemon/DaemonSystemRepository.php b/app/Repositories/Daemon/DaemonSystemRepository.php index 71d88a138..9f2e82ac3 100644 --- a/app/Repositories/Daemon/DaemonSystemRepository.php +++ b/app/Repositories/Daemon/DaemonSystemRepository.php @@ -22,9 +22,7 @@ class DaemonSystemRepository extends DaemonRepository ->get('/api/system') ->throwIf(function ($result) { $this->enforceValidNodeToken($result); - if (!$result->collect()->has(['architecture', 'cpu_count', 'kernel_version', 'os', 'version'])) { - throw new ConnectionException($result->effectiveUri()->__toString() . ' is not Pelican Wings !'); - } + throw_unless($result->collect()->has(['architecture', 'cpu_count', 'kernel_version', 'os', 'version']), new ConnectionException($result->effectiveUri()->__toString() . ' is not Pelican Wings !')); return true; })->json(); diff --git a/app/Services/Allocations/AssignmentService.php b/app/Services/Allocations/AssignmentService.php index 65974e5a3..6fc4e6993 100644 --- a/app/Services/Allocations/AssignmentService.php +++ b/app/Services/Allocations/AssignmentService.php @@ -46,9 +46,7 @@ class AssignmentService { $explode = explode('/', $data['allocation_ip']); if (count($explode) !== 1) { - if (!ctype_digit($explode[1]) || ($explode[1] > self::CIDR_MIN_BITS || $explode[1] < self::CIDR_MAX_BITS)) { - throw new CidrOutOfRangeException(); - } + throw_if(!ctype_digit($explode[1]) || ($explode[1] > self::CIDR_MIN_BITS || $explode[1] < self::CIDR_MAX_BITS), new CidrOutOfRangeException()); } try { @@ -62,21 +60,15 @@ class AssignmentService $ids = []; foreach ($parsed as $ip) { foreach ($data['allocation_ports'] as $port) { - if (!is_digit($port) && !preg_match(self::PORT_RANGE_REGEX, $port)) { - throw new InvalidPortMappingException($port); - } + throw_if(!is_digit($port) && !preg_match(self::PORT_RANGE_REGEX, $port), new InvalidPortMappingException($port)); $newAllocations = []; if (preg_match(self::PORT_RANGE_REGEX, $port, $matches)) { $block = range($matches[1], $matches[2]); - if (count($block) > self::PORT_RANGE_LIMIT) { - throw new TooManyPortsInRangeException(); - } + throw_if(count($block) > self::PORT_RANGE_LIMIT, new TooManyPortsInRangeException()); - if ((int) $matches[1] < self::PORT_FLOOR || (int) $matches[2] > self::PORT_CEIL) { - throw new PortOutOfRangeException(); - } + throw_if((int) $matches[1] < self::PORT_FLOOR || (int) $matches[2] > self::PORT_CEIL, new PortOutOfRangeException()); foreach ($block as $unit) { $newAllocations[] = [ @@ -89,9 +81,7 @@ class AssignmentService ]; } } else { - if ((int) $port < self::PORT_FLOOR || (int) $port > self::PORT_CEIL) { - throw new PortOutOfRangeException(); - } + throw_if((int) $port < self::PORT_FLOOR || (int) $port > self::PORT_CEIL, new PortOutOfRangeException()); $newAllocations[] = [ 'node_id' => $node->id, diff --git a/app/Services/Allocations/FindAssignableAllocationService.php b/app/Services/Allocations/FindAssignableAllocationService.php index 7000dabdf..1d14b3fe6 100644 --- a/app/Services/Allocations/FindAssignableAllocationService.php +++ b/app/Services/Allocations/FindAssignableAllocationService.php @@ -35,9 +35,7 @@ class FindAssignableAllocationService */ public function handle(Server $server): Allocation { - if (!config('panel.client_features.allocations.enabled')) { - throw new AutoAllocationNotEnabledException(); - } + throw_unless(config('panel.client_features.allocations.enabled'), new AutoAllocationNotEnabledException()); $createNew = config('panel.client_features.allocations.create_new', true); @@ -67,9 +65,7 @@ class FindAssignableAllocationService ->first(); // If create_new is disabled, only pick from existing allocations - if (!$createNew && !$allocation) { - throw new NoAutoAllocationSpaceAvailableException(); - } + throw_if(!$createNew && !$allocation, new NoAutoAllocationSpaceAvailableException()); // If create_new is enabled, create a new allocation if none available $allocation ??= $this->createNewAllocation($server, $start, $end); @@ -92,9 +88,7 @@ class FindAssignableAllocationService */ protected function createNewAllocation(Server $server, ?int $start, ?int $end): Allocation { - if (!$start || !$end) { - throw new NoAutoAllocationSpaceAvailableException(); - } + throw_if(!$start || !$end, new NoAutoAllocationSpaceAvailableException()); // Get all the currently allocated ports for the node so that we can figure out // which port might be available. @@ -111,9 +105,7 @@ class FindAssignableAllocationService $available = array_diff(range($start, $end), $ports->toArray()); // If we've already allocated all the ports, just abort. - if (empty($available)) { - throw new NoAutoAllocationSpaceAvailableException(); - } + throw_if(empty($available), new NoAutoAllocationSpaceAvailableException()); // Pick a random port out of the remaining available ports. /** @var int $port */ diff --git a/app/Services/Backups/DeleteBackupService.php b/app/Services/Backups/DeleteBackupService.php index 49090e81c..9f2357112 100644 --- a/app/Services/Backups/DeleteBackupService.php +++ b/app/Services/Backups/DeleteBackupService.php @@ -27,9 +27,7 @@ class DeleteBackupService // I also don't really see any reason you'd have a locked, failed backup to keep // around. The logic that updates the backup to the failed state will also remove // the lock, so this condition should really never happen. - if ($backup->is_locked && ($backup->is_successful && !is_null($backup->completed_at))) { - throw new BackupLockedException(); - } + throw_if($backup->is_locked && ($backup->is_successful && !is_null($backup->completed_at)), new BackupLockedException()); $schema = $this->backupService->get($backup->backupHost->schema); if (!$schema) { diff --git a/app/Services/Backups/InitiateBackupService.php b/app/Services/Backups/InitiateBackupService.php index ba57c241e..6fd1df6fd 100644 --- a/app/Services/Backups/InitiateBackupService.php +++ b/app/Services/Backups/InitiateBackupService.php @@ -95,17 +95,13 @@ class InitiateBackupService $successful = $server->backups()->nonFailed(); if (!$server->backup_limit || $successful->count() >= $server->backup_limit) { // Do not allow the user to continue if this server is already at its limit and can't override. - if (!$override || $server->backup_limit <= 0) { - throw new TooManyBackupsException($server->backup_limit); - } + throw_if(!$override || $server->backup_limit <= 0, new TooManyBackupsException($server->backup_limit)); // Get the oldest backup the server has that is not "locked" (indicating a backup that should // never be automatically purged). If we find a backup we will delete it and then continue with // this process. If no backup is found that can be used an exception is thrown. $oldest = $successful->where('is_locked', false)->orderBy('created_at')->first(); - if (!$oldest) { - throw new TooManyBackupsException($server->backup_limit); - } + throw_unless($oldest, new TooManyBackupsException($server->backup_limit)); $this->deleteBackupService->handle($oldest); } diff --git a/app/Services/Databases/DatabaseManagementService.php b/app/Services/Databases/DatabaseManagementService.php index 55ea8a7b6..09d32e21b 100644 --- a/app/Services/Databases/DatabaseManagementService.php +++ b/app/Services/Databases/DatabaseManagementService.php @@ -70,22 +70,16 @@ class DatabaseManagementService */ public function create(Server $server, array $data): Database { - if (!config('panel.client_features.databases.enabled')) { - throw new DatabaseClientFeatureNotEnabledException(); - } + throw_unless(config('panel.client_features.databases.enabled'), new DatabaseClientFeatureNotEnabledException()); if ($this->validateDatabaseLimit) { // If the server has a limit assigned and we've already reached that limit, throw back // an exception and kill the process. - if (!is_null($server->database_limit) && $server->databases()->count() >= $server->database_limit) { - throw new TooManyDatabasesException(); - } + throw_if(!is_null($server->database_limit) && $server->databases()->count() >= $server->database_limit, new TooManyDatabasesException()); } // Protect against developer mistakes... - if (empty($data['database']) || !preg_match(self::MATCH_NAME_REGEX, $data['database'])) { - throw new InvalidArgumentException('The database name passed to DatabaseManagementService::handle MUST be prefixed with "s{server_id}_".'); - } + throw_if(empty($data['database']) || !preg_match(self::MATCH_NAME_REGEX, $data['database']), new InvalidArgumentException('The database name passed to DatabaseManagementService::handle MUST be prefixed with "s{server_id}_".')); $data = array_merge($data, [ 'server_id' => $server->id, @@ -171,9 +165,7 @@ class DatabaseManagementService ->where('database', $data['database']) ->exists(); - if ($exists) { - throw new DuplicateDatabaseNameException('A database with that name already exists for this server.'); - } + throw_if($exists, new DuplicateDatabaseNameException('A database with that name already exists for this server.')); $database = (new Database())->forceFill($data); $database->saveOrFail(); diff --git a/app/Services/Databases/DeployServerDatabaseService.php b/app/Services/Databases/DeployServerDatabaseService.php index d89e3dc1b..05b3d529a 100644 --- a/app/Services/Databases/DeployServerDatabaseService.php +++ b/app/Services/Databases/DeployServerDatabaseService.php @@ -21,15 +21,11 @@ readonly class DeployServerDatabaseService Assert::notEmpty($data['remote'] ?? null); $hosts = DatabaseHost::query()->get(); - if ($hosts->isEmpty()) { - throw new NoSuitableDatabaseHostException(); - } + throw_if($hosts->isEmpty(), new NoSuitableDatabaseHostException()); $nodeHosts = $server->node->databaseHosts()->get(); // TODO: @areyouscared remove allow random feature for database hosts - if ($nodeHosts->isEmpty() && !config('panel.client_features.databases.allow_random')) { - throw new NoSuitableDatabaseHostException(); - } + throw_if($nodeHosts->isEmpty() && !config('panel.client_features.databases.allow_random'), new NoSuitableDatabaseHostException()); return $this->managementService->create($server, [ 'database_host_id' => $nodeHosts->isEmpty() diff --git a/app/Services/Deployment/AllocationSelectionService.php b/app/Services/Deployment/AllocationSelectionService.php index 3beab139c..ea7ecd460 100644 --- a/app/Services/Deployment/AllocationSelectionService.php +++ b/app/Services/Deployment/AllocationSelectionService.php @@ -63,9 +63,7 @@ class AllocationSelectionService // Ranges are stored in the ports array as an array which can be // better processed in the repository. if (preg_match(AssignmentService::PORT_RANGE_REGEX, $port, $matches)) { - if (abs((int) $matches[2] - (int) $matches[1]) > AssignmentService::PORT_RANGE_LIMIT) { - throw new DisplayException(trans('exceptions.allocations.too_many_ports')); - } + throw_if(((int) $matches[2] - (int) $matches[1] + 1) > AssignmentService::PORT_RANGE_LIMIT, new DisplayException(trans('exceptions.allocations.too_many_ports'))); $stored[] = [$matches[1], $matches[2]]; } @@ -85,9 +83,7 @@ class AllocationSelectionService { $allocation = $this->getRandomAllocation($this->nodes, $this->ports, $this->dedicated); - if (is_null($allocation)) { - throw new NoViableAllocationException(trans('exceptions.deployment.no_viable_allocations')); - } + throw_if(is_null($allocation), new NoViableAllocationException(trans('exceptions.deployment.no_viable_allocations'))); return $allocation; } diff --git a/app/Services/Eggs/Sharing/EggExporterService.php b/app/Services/Eggs/Sharing/EggExporterService.php index 4f702ca82..3544e996a 100644 --- a/app/Services/Eggs/Sharing/EggExporterService.php +++ b/app/Services/Eggs/Sharing/EggExporterService.php @@ -5,7 +5,7 @@ namespace App\Services\Eggs\Sharing; use App\Enums\EggFormat; use App\Models\Egg; use App\Models\EggVariable; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Storage; use Symfony\Component\Yaml\Yaml; diff --git a/app/Services/Eggs/Sharing/EggImporterService.php b/app/Services/Eggs/Sharing/EggImporterService.php index 1f3356d59..9982b4a67 100644 --- a/app/Services/Eggs/Sharing/EggImporterService.php +++ b/app/Services/Eggs/Sharing/EggImporterService.php @@ -52,9 +52,7 @@ class EggImporterService */ public function fromFile(UploadedFile $file, ?Egg $egg = null): Egg { - if ($file->getError() !== UPLOAD_ERR_OK) { - throw new InvalidFileUploadException('The selected file was not uploaded successfully'); - } + throw_if($file->getError() !== UPLOAD_ERR_OK, new InvalidFileUploadException('The selected file was not uploaded successfully')); $extension = strtolower($file->getClientOriginalExtension()); $mime = $file->getMimeType(); @@ -81,9 +79,7 @@ class EggImporterService { $extension = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION)); - if (empty($extension)) { - throw new InvalidFileUploadException('Unsupported file format.'); - } + throw_if(empty($extension), new InvalidFileUploadException('Unsupported file format.')); $format = match ($extension) { 'yaml', 'yml' => EggFormat::YAML, diff --git a/app/Services/Eggs/Variables/VariableCreationService.php b/app/Services/Eggs/Variables/VariableCreationService.php index 1d6c1358a..9ca90d37a 100644 --- a/app/Services/Eggs/Variables/VariableCreationService.php +++ b/app/Services/Eggs/Variables/VariableCreationService.php @@ -44,9 +44,7 @@ class VariableCreationService */ public function handle(int $egg, array $data): EggVariable { - if (in_array(strtoupper(array_get($data, 'env_variable')), EggVariable::RESERVED_ENV_NAMES)) { - throw new ReservedVariableNameException(sprintf('Cannot use the protected name %s for this environment variable.', array_get($data, 'env_variable'))); - } + throw_if(in_array(strtoupper(array_get($data, 'env_variable')), EggVariable::RESERVED_ENV_NAMES), new ReservedVariableNameException(sprintf('Cannot use the protected name %s for this environment variable.', array_get($data, 'env_variable')))); if (!empty($data['rules'] ?? [])) { $this->validateRules($data['rules']); diff --git a/app/Services/Eggs/Variables/VariableUpdateService.php b/app/Services/Eggs/Variables/VariableUpdateService.php index 37fb61ca4..0cdd4aa74 100644 --- a/app/Services/Eggs/Variables/VariableUpdateService.php +++ b/app/Services/Eggs/Variables/VariableUpdateService.php @@ -46,9 +46,7 @@ class VariableUpdateService public function handle(EggVariable $variable, array $data): EggVariable { if (!is_null(array_get($data, 'env_variable'))) { - if (in_array(strtoupper(array_get($data, 'env_variable')), EggVariable::RESERVED_ENV_NAMES)) { - throw new ReservedVariableNameException(trans('exceptions.variables.reserved_name', ['name' => array_get($data, 'env_variable')])); - } + throw_if(in_array(strtoupper(array_get($data, 'env_variable')), EggVariable::RESERVED_ENV_NAMES), new ReservedVariableNameException(trans('exceptions.variables.reserved_name', ['name' => array_get($data, 'env_variable')]))); $search = EggVariable::query() ->where('env_variable', $data['env_variable']) @@ -56,9 +54,7 @@ class VariableUpdateService ->whereNot('id', $variable->id) ->count(); - if ($search > 0) { - throw new DisplayException(trans('exceptions.variables.env_not_unique', ['name' => array_get($data, 'env_variable')])); - } + throw_if($search > 0, new DisplayException(trans('exceptions.variables.env_not_unique', ['name' => array_get($data, 'env_variable')]))); } if (!empty($data['rules'] ?? [])) { diff --git a/app/Services/Helpers/PluginService.php b/app/Services/Helpers/PluginService.php index a19c11156..105211ec1 100644 --- a/app/Services/Helpers/PluginService.php +++ b/app/Services/Helpers/PluginService.php @@ -147,9 +147,7 @@ class PluginService $pluginClass = $plugin->fullClass(); - if (!class_exists($pluginClass)) { - throw new Exception('Class "' . $pluginClass . '" not found'); - } + throw_unless(class_exists($pluginClass), new Exception('Class "' . $pluginClass . '" not found')); $panel->plugin(new $pluginClass()); @@ -199,9 +197,7 @@ class PluginService if (count($oldPackages) > 0) { $result = Process::path(base_path())->timeout(600)->run(['composer', 'remove', ...$oldPackages]); - if ($result->failed()) { - throw new Exception('Could not remove old composer packages: ' . $result->errorOutput()); - } + throw_if($result->failed(), new Exception('Could not remove old composer packages: ' . $result->errorOutput())); } $newPackages = collect($newPackages) @@ -212,9 +208,7 @@ class PluginService if (count($newPackages) > 0) { $result = Process::path(base_path())->timeout(600)->run(['composer', 'require', ...$newPackages]); - if ($result->failed()) { - throw new Exception('Could not require new composer packages: ' . $result->errorOutput()); - } + throw_if($result->failed(), new Exception('Could not require new composer packages: ' . $result->errorOutput())); } } @@ -265,20 +259,14 @@ class PluginService { try { $result = Process::path(base_path())->timeout(300)->run('yarn install'); - if ($result->failed()) { - throw new Exception('Could not install yarn dependencies: ' . $result->errorOutput()); - } + throw_if($result->failed(), new Exception('Could not install yarn dependencies: ' . $result->errorOutput())); $result = Process::path(base_path())->timeout(600)->run('yarn build'); - if ($result->failed()) { - throw new Exception('Could not build assets: ' . $result->errorOutput()); - } + throw_if($result->failed(), new Exception('Could not build assets: ' . $result->errorOutput())); return true; } catch (Exception $exception) { - if ($throw || $this->isDevModeActive()) { - throw ($exception); - } + throw_if($throw || $this->isDevModeActive(), ($exception)); Log::warning($exception->getMessage(), ['exception' => $exception]); } @@ -320,9 +308,7 @@ class PluginService public function updatePlugin(Plugin $plugin): void { $downloadUrl = $plugin->getDownloadUrlForUpdate(); - if (!$downloadUrl) { - throw new Exception('No download url found.'); - } + throw_unless($downloadUrl, new Exception('No download url found.')); $this->downloadPluginFromUrl($downloadUrl, true); @@ -361,15 +347,11 @@ class PluginService { // Validate file size to prevent zip bombs $maxSize = config('panel.plugin.max_import_size'); - if ($file->getSize() > $maxSize) { - throw new Exception("Zip file too large. ($maxSize MiB)"); - } + throw_if($file->getSize() > $maxSize, new Exception("Zip file too large. ($maxSize MiB)")); $zip = new ZipArchive(); - if (!$zip->open($file->getPathname())) { - throw new Exception('Could not open zip file.'); - } + throw_unless($zip->open($file->getPathname()), new Exception('Could not open zip file.')); // Validate zip contents before extraction for ($i = 0; $i < $zip->numFiles; $i++) { @@ -407,13 +389,9 @@ class PluginService // Validate file size to prevent zip bombs $maxSize = config('panel.plugin.max_import_size'); - if (strlen($content) > $maxSize) { - throw new InvalidFileUploadException("Zip file too large. ($maxSize MiB)"); - } + throw_if(strlen($content) > $maxSize, new InvalidFileUploadException("Zip file too large. ($maxSize MiB)")); - if (!file_put_contents($tmpPath, $content)) { - throw new InvalidFileUploadException('Could not write temporary file.'); - } + throw_unless(file_put_contents($tmpPath, $content), new InvalidFileUploadException('Could not write temporary file.')); $this->downloadPluginFromFile(new UploadedFile($tmpPath, $basename, 'application/zip'), $cleanDownload); } @@ -509,9 +487,7 @@ class PluginService private function handlePluginException(Plugin $plugin, Exception $exception): void { - if ($this->isDevModeActive()) { - throw ($exception); - } + throw_if($this->isDevModeActive(), ($exception)); report($exception); diff --git a/app/Services/Nodes/NodeDeletionService.php b/app/Services/Nodes/NodeDeletionService.php index 4224937b6..b05b69a06 100644 --- a/app/Services/Nodes/NodeDeletionService.php +++ b/app/Services/Nodes/NodeDeletionService.php @@ -18,9 +18,7 @@ class NodeDeletionService $node = Node::findOrFail($node); } - if ($node->servers()->count() > 0) { - throw new HasActiveServersException(trans('exceptions.node.servers_attached')); - } + throw_if($node->servers()->count() > 0, new HasActiveServersException(trans('exceptions.node.servers_attached'))); return (int) $node->delete(); } diff --git a/app/Services/Nodes/NodeUpdateService.php b/app/Services/Nodes/NodeUpdateService.php index 1f7123bb2..227163a00 100644 --- a/app/Services/Nodes/NodeUpdateService.php +++ b/app/Services/Nodes/NodeUpdateService.php @@ -61,9 +61,7 @@ class NodeUpdateService return [$updated, false]; }); - if ($exception) { - throw new ConfigurationNotPersistedException(trans('exceptions.node.daemon_off_config_updated')); - } + throw_if($exception, new ConfigurationNotPersistedException(trans('exceptions.node.daemon_off_config_updated'))); return $updated; } diff --git a/app/Services/Schedules/ProcessScheduleService.php b/app/Services/Schedules/ProcessScheduleService.php index 12eb8267b..3852bf41e 100644 --- a/app/Services/Schedules/ProcessScheduleService.php +++ b/app/Services/Schedules/ProcessScheduleService.php @@ -23,9 +23,7 @@ class ProcessScheduleService { $task = $schedule->firstTask(); - if (!$task) { - throw new DisplayException('Cannot process schedule for task execution: no tasks are registered.'); - } + throw_unless($task, new DisplayException('Cannot process schedule for task execution: no tasks are registered.')); $this->connection->transaction(function () use ($schedule, $task) { $schedule->forceFill([ diff --git a/app/Services/Schedules/Sharing/ScheduleImporterService.php b/app/Services/Schedules/Sharing/ScheduleImporterService.php index d8633275e..de5857023 100644 --- a/app/Services/Schedules/Sharing/ScheduleImporterService.php +++ b/app/Services/Schedules/Sharing/ScheduleImporterService.php @@ -20,9 +20,7 @@ class ScheduleImporterService public function fromFile(UploadedFile $file, Server $server): Schedule { - if ($file->getError() !== UPLOAD_ERR_OK) { - throw new InvalidFileUploadException('The selected file was not uploaded successfully'); - } + throw_if($file->getError() !== UPLOAD_ERR_OK, new InvalidFileUploadException('The selected file was not uploaded successfully')); try { $parsed = json_decode($file->getContent(), true, 512, JSON_THROW_ON_ERROR); @@ -73,9 +71,7 @@ class ScheduleImporterService $fileContents = Http::timeout(5)->connectTimeout(1)->get($url)->throw()->body(); - if (!$fileContents || !file_put_contents($tmpPath, $fileContents)) { - throw new InvalidFileUploadException('Could not write temporary file.'); - } + throw_if(!$fileContents || !file_put_contents($tmpPath, $fileContents), new InvalidFileUploadException('Could not write temporary file.')); return $this->fromFile(new UploadedFile($tmpPath, $basename, 'application/json'), $server); } diff --git a/app/Services/Servers/ServerCreationService.php b/app/Services/Servers/ServerCreationService.php index f15f84f34..5dda00fc5 100644 --- a/app/Services/Servers/ServerCreationService.php +++ b/app/Services/Servers/ServerCreationService.php @@ -73,9 +73,7 @@ class ServerCreationService $deployment->getTags(), )->pluck('id'); - if ($nodes->isEmpty()) { - throw new NoViableNodeException(trans('exceptions.deployment.no_viable_nodes')); - } + throw_if($nodes->isEmpty(), new NoViableNodeException(trans('exceptions.deployment.no_viable_nodes'))); $ports = $deployment->getPorts(); if (!empty($ports)) { diff --git a/app/Services/Servers/ToggleInstallService.php b/app/Services/Servers/ToggleInstallService.php index 770db8443..e3710a691 100644 --- a/app/Services/Servers/ToggleInstallService.php +++ b/app/Services/Servers/ToggleInstallService.php @@ -9,9 +9,7 @@ class ToggleInstallService { public function handle(Server $server): void { - if ($server->isFailedInstall()) { - abort(500, trans('exceptions.server.marked_as_failed')); - } + abort_if($server->isFailedInstall(), 500, trans('exceptions.server.marked_as_failed')); $server->status = $server->isInstalled() ? ServerState::Installing : null; $server->save(); diff --git a/app/Services/Servers/VariableValidatorService.php b/app/Services/Servers/VariableValidatorService.php index a20550a30..a87c6cff7 100644 --- a/app/Services/Servers/VariableValidatorService.php +++ b/app/Services/Servers/VariableValidatorService.php @@ -42,9 +42,7 @@ class VariableValidatorService } $validator = $this->validator->make($data, $rules, [], $customAttributes); - if ($validator->fails()) { - throw new ValidationException($validator); - } + throw_if($validator->fails(), new ValidationException($validator)); return Collection::make($variables)->map(function ($item) use ($fields) { return (object) [ diff --git a/app/Services/Ssh/KeyCreationService.php b/app/Services/Ssh/KeyCreationService.php index 4bd9f7faa..391c0fae0 100644 --- a/app/Services/Ssh/KeyCreationService.php +++ b/app/Services/Ssh/KeyCreationService.php @@ -23,18 +23,12 @@ class KeyCreationService throw new Exception('The public key provided is not valid'); } - if ($key instanceof DSA) { - throw new Exception('DSA keys are not supported'); - } + throw_if($key instanceof DSA, new Exception('DSA keys are not supported')); - if ($key instanceof RSA && $key->getLength() < 2048) { - throw new Exception('RSA keys must be at least 2048 bytes in length'); - } + throw_if($key instanceof RSA && $key->getLength() < 2048, new Exception('RSA keys must be at least 2048 bytes in length')); $fingerprint = $key->getFingerprint('sha256'); - if ($user->sshKeys()->where('fingerprint', $fingerprint)->exists()) { - throw new Exception('The public key provided already exists on your account'); - } + throw_if($user->sshKeys()->where('fingerprint', $fingerprint)->exists(), new Exception('The public key provided already exists on your account')); /** @var UserSSHKey $sshKey */ $sshKey = $user->sshKeys()->create([ diff --git a/app/Services/Subusers/SubuserCreationService.php b/app/Services/Subusers/SubuserCreationService.php index 61d8ba007..213b82174 100644 --- a/app/Services/Subusers/SubuserCreationService.php +++ b/app/Services/Subusers/SubuserCreationService.php @@ -46,14 +46,10 @@ class SubuserCreationService 'root_admin' => false, ]); } else { - if ($server->owner_id === $user->id) { - throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner')); - } + throw_if($server->owner_id === $user->id, new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner'))); $subuserCount = $server->subusers()->where('user_id', $user->id)->count(); - if ($subuserCount !== 0) { - throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists')); - } + throw_if($subuserCount !== 0, new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists'))); } $cleanedPermissions = collect($permissions) diff --git a/app/Traits/HasValidation.php b/app/Traits/HasValidation.php index 2d2f0e0c1..78cdb0e4a 100644 --- a/app/Traits/HasValidation.php +++ b/app/Traits/HasValidation.php @@ -101,8 +101,6 @@ trait HasValidation ) ); - if (!$validator->passes()) { - throw new ValidationException($validator); - } + throw_unless($validator->passes(), new ValidationException($validator)); } } diff --git a/app/Transformers/Api/Client/EggVariableTransformer.php b/app/Transformers/Api/Client/EggVariableTransformer.php index 231c534e1..872c35af9 100644 --- a/app/Transformers/Api/Client/EggVariableTransformer.php +++ b/app/Transformers/Api/Client/EggVariableTransformer.php @@ -20,9 +20,7 @@ class EggVariableTransformer extends BaseClientTransformer // This guards against someone incorrectly retrieving variables (haha, me) and then passing // them into the transformer and along to the user. Just throw an exception and break the entire // pathway since you should never be exposing these types of variables to a client. - if (!$variable->user_viewable) { - throw new BadMethodCallException('Cannot transform a hidden egg variable in a client transformer.'); - } + throw_unless($variable->user_viewable, new BadMethodCallException('Cannot transform a hidden egg variable in a client transformer.')); return [ 'name' => $variable->name, diff --git a/app/Transformers/Api/Client/FileObjectTransformer.php b/app/Transformers/Api/Client/FileObjectTransformer.php index b8ebdbd56..c839f7206 100644 --- a/app/Transformers/Api/Client/FileObjectTransformer.php +++ b/app/Transformers/Api/Client/FileObjectTransformer.php @@ -2,8 +2,8 @@ namespace App\Transformers\Api\Client; -use Carbon\Carbon; use Illuminate\Support\Arr; +use Illuminate\Support\Carbon; class FileObjectTransformer extends BaseClientTransformer { diff --git a/database/Factories/ApiKeyFactory.php b/database/Factories/ApiKeyFactory.php index c119d359c..581f4a334 100644 --- a/database/Factories/ApiKeyFactory.php +++ b/database/Factories/ApiKeyFactory.php @@ -3,8 +3,8 @@ namespace Database\Factories; use App\Models\ApiKey; -use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; class ApiKeyFactory extends Factory diff --git a/database/Factories/DatabaseFactory.php b/database/Factories/DatabaseFactory.php index 6c1830fe7..78a972cd0 100644 --- a/database/Factories/DatabaseFactory.php +++ b/database/Factories/DatabaseFactory.php @@ -3,8 +3,8 @@ namespace Database\Factories; use App\Models\Database; -use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; class DatabaseFactory extends Factory diff --git a/database/Factories/ServerFactory.php b/database/Factories/ServerFactory.php index 98ebe36e7..a64fb426d 100644 --- a/database/Factories/ServerFactory.php +++ b/database/Factories/ServerFactory.php @@ -7,8 +7,8 @@ use App\Models\Egg; use App\Models\Node; use App\Models\Server; use App\Models\User; -use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; use Ramsey\Uuid\Uuid; diff --git a/database/Factories/UserFactory.php b/database/Factories/UserFactory.php index 0d43631c6..38833486b 100644 --- a/database/Factories/UserFactory.php +++ b/database/Factories/UserFactory.php @@ -3,8 +3,8 @@ namespace Database\Factories; use App\Models\User; -use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; use Ramsey\Uuid\Uuid; diff --git a/database/migrations/2017_09_11_002938_TransferOldTasksToNewScheduler.php b/database/migrations/2017_09_11_002938_TransferOldTasksToNewScheduler.php index cf7786752..aa5370a1e 100644 --- a/database/migrations/2017_09_11_002938_TransferOldTasksToNewScheduler.php +++ b/database/migrations/2017_09_11_002938_TransferOldTasksToNewScheduler.php @@ -1,8 +1,8 @@ engine('InnoDB'); @@ -127,9 +123,7 @@ return new class extends Migration { $tableNames = config('permission.table_names'); - if (empty($tableNames)) { - throw new Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.'); - } + throw_if(empty($tableNames), new Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.')); Schema::drop($tableNames['role_has_permissions']); Schema::drop($tableNames['model_has_roles']); diff --git a/tests/Integration/Jobs/Schedule/RunTaskJobTest.php b/tests/Integration/Jobs/Schedule/RunTaskJobTest.php index 64dab5a18..923b38487 100644 --- a/tests/Integration/Jobs/Schedule/RunTaskJobTest.php +++ b/tests/Integration/Jobs/Schedule/RunTaskJobTest.php @@ -9,9 +9,9 @@ use App\Models\Server; use App\Models\Task; use App\Repositories\Daemon\DaemonServerRepository; use App\Tests\Integration\IntegrationTestCase; -use Carbon\Carbon; use Carbon\CarbonImmutable; use Illuminate\Http\Client\ConnectionException; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Bus; use PHPUnit\Framework\Attributes\DataProvider; diff --git a/tests/TestCase.php b/tests/TestCase.php index ecba942ee..84f01d3a0 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -3,10 +3,10 @@ namespace App\Tests; use App\Tests\Seeders\EggSeeder; -use Carbon\Carbon; use Carbon\CarbonImmutable; use Exception; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; +use Illuminate\Support\Carbon; use Spatie\Permission\PermissionRegistrar; abstract class TestCase extends BaseTestCase diff --git a/tests/Traits/Http/MocksMiddlewareClosure.php b/tests/Traits/Http/MocksMiddlewareClosure.php index ede0307b6..78617aabc 100644 --- a/tests/Traits/Http/MocksMiddlewareClosure.php +++ b/tests/Traits/Http/MocksMiddlewareClosure.php @@ -13,9 +13,7 @@ trait MocksMiddlewareClosure */ protected function getClosureAssertions(): Closure { - if (is_null($this->request)) { - throw new \BadFunctionCallException('Calling getClosureAssertions without defining a request object is not supported.'); - } + throw_if(is_null($this->request), new \BadFunctionCallException('Calling getClosureAssertions without defining a request object is not supported.')); return function ($response) { $this->assertInstanceOf(Request::class, $response); diff --git a/tests/Traits/Http/RequestMockHelpers.php b/tests/Traits/Http/RequestMockHelpers.php index 9f777f5d7..2337802de 100644 --- a/tests/Traits/Http/RequestMockHelpers.php +++ b/tests/Traits/Http/RequestMockHelpers.php @@ -68,9 +68,7 @@ trait RequestMockHelpers protected function buildRequestMock(): void { $this->request = m::mock($this->requestMockClass); - if (!$this->request instanceof Request) { - throw new \InvalidArgumentException('Request mock class must be an instance of ' . Request::class . ' when mocked.'); - } + throw_unless($this->request instanceof Request, new \InvalidArgumentException('Request mock class must be an instance of ' . Request::class . ' when mocked.')); $this->request->attributes = new ParameterBag(); } diff --git a/tests/Unit/Console/Commands/Egg/NormalizerEggCommandTest.php b/tests/Unit/Console/Commands/Egg/NormalizerEggCommandTest.php index 40c1a7b93..e6438bc75 100644 --- a/tests/Unit/Console/Commands/Egg/NormalizerEggCommandTest.php +++ b/tests/Unit/Console/Commands/Egg/NormalizerEggCommandTest.php @@ -2,8 +2,8 @@ namespace App\Tests\Unit\Console\Commands\Egg { use App\Tests\TestCase; - use Carbon\Carbon; use Carbon\CarbonInterface; + use Illuminate\Support\Carbon; use Illuminate\Testing\PendingCommand; use Symfony\Component\Uid\Uuid; @@ -109,12 +109,9 @@ namespace App\Tests\Unit\Console\Commands\Egg { private function copyExampleFile(string $filename): void { - if (!copy( + throw_unless(copy( dirname(__FILE__) . '/' . $filename, - $this->tmpdir . '/' . $filename) - ) { - throw new \Exception('unable to copy json file to tmpdir'); - } + $this->tmpdir . '/' . $filename), new \Exception('unable to copy json file to tmpdir')); } protected function setUp(): void @@ -124,9 +121,7 @@ namespace App\Tests\Unit\Console\Commands\Egg { register_shutdown_function([$this, 'shutdownHandler']); $this->tmpdir = sys_get_temp_dir() . '/' . Uuid::v4()->toRfc4122(); - if (!mkdir($this->tmpdir)) { - throw new \Exception('unable to create tmp dir'); - } + throw_unless(mkdir($this->tmpdir), new \Exception('unable to create tmp dir')); // save the datetime set by the test framework to restore it after out tests $this->origTime = Carbon::getTestNow();