diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml new file mode 100644 index 0000000..f0f6471 --- /dev/null +++ b/.github/workflows/code-quality.yml @@ -0,0 +1,42 @@ +name: code-quality + +on: + push: + branches: + - 2.x + pull_request: + branches: + - 2.x + +jobs: + tests: + runs-on: ubuntu-22.04 + + strategy: + fail-fast: true + matrix: + php: [ 8.2 ] + + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + + - name: Cache Composer packages + id: composer-cache + uses: actions/cache@v4 + with: + path: vendor + key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-php- + + - name: Install dependencies + if: steps.composer-cache.outputs.cache-hit != 'true' + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Run PHPStan + run: ./vendor/bin/phpstan analyse diff --git a/app/Actions/CronJob/CreateCronJob.php b/app/Actions/CronJob/CreateCronJob.php index 6307d09..5604073 100755 --- a/app/Actions/CronJob/CreateCronJob.php +++ b/app/Actions/CronJob/CreateCronJob.php @@ -10,6 +10,9 @@ class CreateCronJob { + /** + * @param array $input + */ public function create(Server $server, array $input): CronJob { $cronJob = new CronJob([ @@ -28,6 +31,10 @@ public function create(Server $server, array $input): CronJob return $cronJob; } + /** + * @param array $input + * @return array> + */ public static function rules(array $input, Server $server): array { $rules = [ diff --git a/app/Actions/Database/CreateDatabase.php b/app/Actions/Database/CreateDatabase.php index fe2632f..79cbb77 100755 --- a/app/Actions/Database/CreateDatabase.php +++ b/app/Actions/Database/CreateDatabase.php @@ -5,11 +5,15 @@ use App\Enums\DatabaseStatus; use App\Models\Database; use App\Models\Server; +use App\Models\Service; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; class CreateDatabase { + /** + * @param array $input + */ public function create(Server $server, array $input): Database { $database = new Database([ @@ -18,8 +22,12 @@ public function create(Server $server, array $input): Database 'collation' => $input['collation'], 'name' => $input['name'], ]); + + /** @var Service $service */ + $service = $server->database(); + /** @var \App\SSH\Services\Database\Database $databaseHandler */ - $databaseHandler = $server->database()->handler(); + $databaseHandler = $service->handler(); $databaseHandler->create($database->name, $database->charset, $database->collation); $database->status = DatabaseStatus::READY; $database->save(); @@ -34,6 +42,9 @@ public function create(Server $server, array $input): Database } /** + * @param array $input + * @return array + * * @throws ValidationException */ public static function rules(Server $server, array $input): array diff --git a/app/Actions/Database/CreateDatabaseUser.php b/app/Actions/Database/CreateDatabaseUser.php index 66cbfc5..59b7a86 100755 --- a/app/Actions/Database/CreateDatabaseUser.php +++ b/app/Actions/Database/CreateDatabaseUser.php @@ -5,6 +5,7 @@ use App\Enums\DatabaseUserStatus; use App\Models\DatabaseUser; use App\Models\Server; +use App\Models\Service; use App\SSH\Services\Database\Database; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; @@ -12,6 +13,9 @@ class CreateDatabaseUser { /** + * @param array $input + * @param array $links + * * @throws ValidationException */ public function create(Server $server, array $input, array $links = []): DatabaseUser @@ -23,8 +27,12 @@ public function create(Server $server, array $input, array $links = []): Databas 'host' => (isset($input['remote']) && $input['remote']) || isset($input['host']) ? $input['host'] : 'localhost', 'databases' => $links, ]); + + /** @var Service $service */ + $service = $server->database(); + /** @var Database $databaseHandler */ - $databaseHandler = $server->database()->handler(); + $databaseHandler = $service->handler(); $databaseHandler->createUser( $databaseUser->username, $databaseUser->password, @@ -41,6 +49,9 @@ public function create(Server $server, array $input, array $links = []): Databas } /** + * @param array $input + * @return array + * * @throws ValidationException */ public static function rules(Server $server, array $input): array diff --git a/app/Actions/Database/DeleteDatabase.php b/app/Actions/Database/DeleteDatabase.php index c8d49f8..afb8983 100755 --- a/app/Actions/Database/DeleteDatabase.php +++ b/app/Actions/Database/DeleteDatabase.php @@ -4,12 +4,17 @@ use App\Models\Database; use App\Models\Server; +use App\Models\Service; class DeleteDatabase { public function delete(Server $server, Database $database): void { - $server->database()->handler()->delete($database->name); + /** @var Service $service */ + $service = $server->database(); + /** @var \App\SSH\Services\Database\Database $handler */ + $handler = $service->handler(); + $handler->delete($database->name); $database->delete(); } } diff --git a/app/Actions/Database/DeleteDatabaseUser.php b/app/Actions/Database/DeleteDatabaseUser.php index 8b70433..5993c3b 100755 --- a/app/Actions/Database/DeleteDatabaseUser.php +++ b/app/Actions/Database/DeleteDatabaseUser.php @@ -4,12 +4,18 @@ use App\Models\DatabaseUser; use App\Models\Server; +use App\Models\Service; +use App\SSH\Services\Database\Database; class DeleteDatabaseUser { public function delete(Server $server, DatabaseUser $databaseUser): void { - $server->database()->handler()->deleteUser($databaseUser->username, $databaseUser->host); + /** @var Service $service */ + $service = $server->database(); + /** @var Database $handler */ + $handler = $service->handler(); + $handler->deleteUser($databaseUser->username, $databaseUser->host); $databaseUser->delete(); } } diff --git a/app/Actions/Database/LinkUser.php b/app/Actions/Database/LinkUser.php index 8b5e8a0..5a9f53c 100755 --- a/app/Actions/Database/LinkUser.php +++ b/app/Actions/Database/LinkUser.php @@ -5,12 +5,16 @@ use App\Models\Database; use App\Models\DatabaseUser; use App\Models\Server; +use App\Models\Service; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; class LinkUser { /** + * @param array $input + * @return DatabaseUser $databaseUser + * * @throws ValidationException */ public function link(DatabaseUser $databaseUser, array $input): DatabaseUser @@ -29,14 +33,20 @@ public function link(DatabaseUser $databaseUser, array $input): DatabaseUser $databaseUser->databases = $input['databases']; + /** @var Service $service */ + $service = $databaseUser->server->database(); + + /** @var \App\SSH\Services\Database\Database $handler */ + $handler = $service->handler(); + // Unlink the user from all databases - $databaseUser->server->database()->handler()->unlink( + $handler->unlink( $databaseUser->username, $databaseUser->host ); // Link the user to the selected databases - $databaseUser->server->database()->handler()->link( + $handler->link( $databaseUser->username, $databaseUser->host, $databaseUser->databases @@ -49,6 +59,10 @@ public function link(DatabaseUser $databaseUser, array $input): DatabaseUser return $databaseUser; } + /** + * @param array $input + * @return array + */ public static function rules(Server $server, array $input): array { return [ diff --git a/app/Actions/Database/ManageBackup.php b/app/Actions/Database/ManageBackup.php index 0fe7f72..954bac1 100644 --- a/app/Actions/Database/ManageBackup.php +++ b/app/Actions/Database/ManageBackup.php @@ -14,6 +14,8 @@ class ManageBackup { /** + * @param array $input + * * @throws AuthorizationException * @throws ValidationException */ @@ -35,6 +37,9 @@ public function create(Server $server, array $input): Backup return $backup; } + /** + * @param array $input + */ public function update(Backup $backup, array $input): void { $backup->interval = $input['interval'] == 'custom' ? $input['custom_interval'] : $input['interval']; @@ -47,7 +52,7 @@ public function delete(Backup $backup): void $backup->status = BackupStatus::DELETING; $backup->save(); - dispatch(function () use ($backup) { + dispatch(function () use ($backup): void { $files = $backup->files; foreach ($files as $file) { $file->status = BackupFileStatus::DELETING; @@ -60,6 +65,10 @@ public function delete(Backup $backup): void }); } + /** + * @param array $input + * @return array + */ public static function rules(Server $server, array $input): array { $rules = [ diff --git a/app/Actions/Database/ManageBackupFile.php b/app/Actions/Database/ManageBackupFile.php index 7988cbf..9d9bf38 100644 --- a/app/Actions/Database/ManageBackupFile.php +++ b/app/Actions/Database/ManageBackupFile.php @@ -28,7 +28,7 @@ public function delete(BackupFile $file): void $file->status = BackupFileStatus::DELETING; $file->save(); - dispatch(function () use ($file) { + dispatch(function () use ($file): void { $file->deleteFile(); }); } diff --git a/app/Actions/Database/RestoreBackup.php b/app/Actions/Database/RestoreBackup.php index 17de5c7..535b59d 100644 --- a/app/Actions/Database/RestoreBackup.php +++ b/app/Actions/Database/RestoreBackup.php @@ -5,9 +5,13 @@ use App\Enums\BackupFileStatus; use App\Models\BackupFile; use App\Models\Database; +use App\Models\Service; class RestoreBackup { + /** + * @param array $input + */ public function restore(BackupFile $backupFile, array $input): void { /** @var Database $database */ @@ -16,19 +20,24 @@ public function restore(BackupFile $backupFile, array $input): void $backupFile->restored_to = $database->name; $backupFile->save(); - dispatch(function () use ($backupFile, $database) { + dispatch(function () use ($backupFile, $database): void { + /** @var Service $service */ + $service = $database->server->database(); /** @var \App\SSH\Services\Database\Database $databaseHandler */ - $databaseHandler = $database->server->database()->handler(); + $databaseHandler = $service->handler(); $databaseHandler->restoreBackup($backupFile, $database->name); $backupFile->status = BackupFileStatus::RESTORED; $backupFile->restored_at = now(); $backupFile->save(); - })->catch(function () use ($backupFile) { + })->catch(function () use ($backupFile): void { $backupFile->status = BackupFileStatus::RESTORE_FAILED; $backupFile->save(); })->onConnection('ssh'); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Database/RunBackup.php b/app/Actions/Database/RunBackup.php index 6819c91..20935e7 100644 --- a/app/Actions/Database/RunBackup.php +++ b/app/Actions/Database/RunBackup.php @@ -6,6 +6,7 @@ use App\Enums\BackupStatus; use App\Models\Backup; use App\Models\BackupFile; +use App\Models\Service; use App\SSH\Services\Database\Database; use Illuminate\Support\Str; @@ -20,9 +21,11 @@ public function run(Backup $backup): BackupFile ]); $file->save(); - dispatch(function () use ($file, $backup) { + dispatch(function () use ($file, $backup): void { + /** @var Service $service */ + $service = $backup->server->database(); /** @var Database $databaseHandler */ - $databaseHandler = $file->backup->server->database()->handler(); + $databaseHandler = $service->handler(); $databaseHandler->runBackup($file); $file->status = BackupFileStatus::CREATED; $file->save(); @@ -31,7 +34,7 @@ public function run(Backup $backup): BackupFile $backup->status = BackupStatus::RUNNING; $backup->save(); } - })->catch(function () use ($file, $backup) { + })->catch(function () use ($file, $backup): void { $backup->status = BackupStatus::FAILED; $backup->save(); $file->status = BackupFileStatus::FAILED; diff --git a/app/Actions/FileManager/FetchFiles.php b/app/Actions/FileManager/FetchFiles.php index 77aeca0..56f4aa9 100644 --- a/app/Actions/FileManager/FetchFiles.php +++ b/app/Actions/FileManager/FetchFiles.php @@ -11,6 +11,8 @@ class FetchFiles { /** + * @param array $input + * * @throws SSHError */ public function fetch(User $user, Server $server, array $input): void @@ -24,6 +26,9 @@ public function fetch(User $user, Server $server, array $input): void ); } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/FirewallRule/ManageRule.php b/app/Actions/FirewallRule/ManageRule.php index 9fad76f..a855a6c 100755 --- a/app/Actions/FirewallRule/ManageRule.php +++ b/app/Actions/FirewallRule/ManageRule.php @@ -5,10 +5,16 @@ use App\Enums\FirewallRuleStatus; use App\Models\FirewallRule; use App\Models\Server; +use App\Models\Service; use App\SSH\Services\Firewall\Firewall; +use Exception; class ManageRule { + /** + * @param array $input + * @return FirewallRule $rule + */ public function create(Server $server, array $input): FirewallRule { $sourceAny = $input['source_any'] ?? empty($input['source'] ?? null); @@ -30,6 +36,10 @@ public function create(Server $server, array $input): FirewallRule return $rule; } + /** + * @param array $input + * @return FirewallRule $rule + */ public function update(FirewallRule $rule, array $input): FirewallRule { $sourceAny = $input['source_any'] ?? empty($input['source'] ?? null); @@ -56,18 +66,20 @@ public function delete(FirewallRule $rule): void dispatch(fn () => $this->applyRule($rule)); } - protected function applyRule($rule): void + protected function applyRule(FirewallRule $rule): void { try { + /** @var Service $service */ + $service = $rule->server->firewall(); /** @var Firewall $handler */ - $handler = $rule->server->firewall()->handler(); + $handler = $service->handler(); $handler->applyRules(); - } catch (\Exception $e) { + } catch (Exception) { $rule->server->firewallRules() ->where('status', '!=', FirewallRuleStatus::READY) ->update(['status' => FirewallRuleStatus::FAILED]); - throw $e; + return; } if ($rule->status === FirewallRuleStatus::DELETING) { @@ -80,6 +92,9 @@ protected function applyRule($rule): void $rule->save(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Monitoring/GetMetrics.php b/app/Actions/Monitoring/GetMetrics.php index ec5f5c5..3521bb7 100644 --- a/app/Actions/Monitoring/GetMetrics.php +++ b/app/Actions/Monitoring/GetMetrics.php @@ -11,6 +11,10 @@ class GetMetrics { + /** + * @param array $input + * @return Collection + */ public function filter(Server $server, array $input): Collection { if (isset($input['from']) && isset($input['to']) && $input['from'] === $input['to']) { @@ -32,6 +36,9 @@ public function filter(Server $server, array $input): Collection ); } + /** + * @return Collection + */ private function metrics( Server $server, Carbon $fromDate, @@ -57,13 +64,16 @@ private function metrics( ->groupByRaw('date_interval') ->orderBy('date_interval') ->get() - ->map(function ($item) { + ->map(function ($item): \stdClass { $item->date = Carbon::parse($item->date)->format('Y-m-d H:i'); return $item; }); } + /** + * @param array $input + */ private function getFromDate(array $input): Carbon { if ($input['period'] === 'custom') { @@ -73,6 +83,9 @@ private function getFromDate(array $input): Carbon return Carbon::parse('-'.convert_time_format($input['period'])); } + /** + * @param array $input + */ private function getToDate(array $input): Carbon { if ($input['period'] === 'custom') { @@ -82,6 +95,9 @@ private function getToDate(array $input): Carbon return Carbon::now(); } + /** + * @param array $input + */ private function getInterval(array $input): Expression { if ($input['period'] === 'custom') { @@ -107,6 +123,10 @@ private function getInterval(array $input): Expression return DB::raw("strftime('%Y-%m-%d 00:00:00', created_at) as date_interval"); } + /** + * @param array $input + * @return array> + */ public static function rules(array $input): array { $rules = [ diff --git a/app/Actions/Monitoring/UpdateMetricSettings.php b/app/Actions/Monitoring/UpdateMetricSettings.php index d4f5d63..707f547 100644 --- a/app/Actions/Monitoring/UpdateMetricSettings.php +++ b/app/Actions/Monitoring/UpdateMetricSettings.php @@ -3,19 +3,29 @@ namespace App\Actions\Monitoring; use App\Models\Server; +use App\Models\Service; +use App\SSH\Services\ServiceInterface; class UpdateMetricSettings { + /** + * @param array $input + */ public function update(Server $server, array $input): void { + /** @var Service $service */ $service = $server->monitoring(); - - $data = $service->handler()->data(); + /** @var ServiceInterface $handler */ + $handler = $service->handler(); + $data = $handler->data(); $data['data_retention'] = $input['data_retention']; $service->type_data = $data; $service->save(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/NodeJS/ChangeDefaultCli.php b/app/Actions/NodeJS/ChangeDefaultCli.php index 16b41c0..121d437 100644 --- a/app/Actions/NodeJS/ChangeDefaultCli.php +++ b/app/Actions/NodeJS/ChangeDefaultCli.php @@ -3,24 +3,38 @@ namespace App\Actions\NodeJS; use App\Enums\ServiceStatus; +use App\Exceptions\SSHError; use App\Models\Server; +use App\Models\Service; use App\SSH\Services\NodeJS\NodeJS; use Illuminate\Validation\ValidationException; class ChangeDefaultCli { + /** + * @param array $input + * + * @throws ValidationException + * @throws SSHError + */ public function change(Server $server, array $input): void { $this->validate($server, $input); + /** @var Service $service */ $service = $server->nodejs($input['version']); /** @var NodeJS $handler */ $handler = $service->handler(); $handler->setDefaultCli(); - $server->defaultService('nodejs')->update(['is_default' => 0]); + $server->defaultService('nodejs')?->update(['is_default' => 0]); $service->update(['is_default' => 1]); $service->update(['status' => ServiceStatus::READY]); } + /** + * @param array $input + * + * @throws ValidationException + */ public function validate(Server $server, array $input): void { if (! isset($input['version']) || ! in_array($input['version'], $server->installedNodejsVersions())) { diff --git a/app/Actions/NodeJS/InstallNewNodeJsVersion.php b/app/Actions/NodeJS/InstallNewNodeJsVersion.php index e5c0eba..d9cfdea 100755 --- a/app/Actions/NodeJS/InstallNewNodeJsVersion.php +++ b/app/Actions/NodeJS/InstallNewNodeJsVersion.php @@ -10,6 +10,9 @@ class InstallNewNodeJsVersion { + /** + * @param array $input + */ public function install(Server $server, array $input): void { $nodejs = new Service([ @@ -23,15 +26,18 @@ public function install(Server $server, array $input): void ]); $nodejs->save(); - dispatch(function () use ($nodejs) { + dispatch(function () use ($nodejs): void { $nodejs->handler()->install(); $nodejs->status = ServiceStatus::READY; $nodejs->save(); - })->catch(function () use ($nodejs) { + })->catch(function () use ($nodejs): void { $nodejs->delete(); })->onConnection('ssh'); } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/NodeJS/UninstallNodeJS.php b/app/Actions/NodeJS/UninstallNodeJS.php index 8e5bd5a..4edde1a 100755 --- a/app/Actions/NodeJS/UninstallNodeJS.php +++ b/app/Actions/NodeJS/UninstallNodeJS.php @@ -10,6 +10,11 @@ class UninstallNodeJS { + /** + * @param array $input + * + * @throws ValidationException + */ public function uninstall(Server $server, array $input): void { $this->validate($server, $input); @@ -19,16 +24,18 @@ public function uninstall(Server $server, array $input): void $nodejs->status = ServiceStatus::UNINSTALLING; $nodejs->save(); - dispatch(function () use ($nodejs) { + dispatch(function () use ($nodejs): void { $nodejs->handler()->uninstall(); $nodejs->delete(); - })->catch(function () use ($nodejs) { + })->catch(function () use ($nodejs): void { $nodejs->status = ServiceStatus::FAILED; $nodejs->save(); })->onConnection('ssh'); } /** + * @param array $input + * * @throws ValidationException */ private function validate(Server $server, array $input): void diff --git a/app/Actions/NotificationChannels/AddChannel.php b/app/Actions/NotificationChannels/AddChannel.php index 0104cfb..24a5b70 100644 --- a/app/Actions/NotificationChannels/AddChannel.php +++ b/app/Actions/NotificationChannels/AddChannel.php @@ -11,8 +11,9 @@ class AddChannel { /** + * @param array $input + * * @throws ValidationException - * @throws Exception */ public function add(User $user, array $input): void { @@ -42,13 +43,19 @@ public function add(User $user, array $input): void } catch (Exception $e) { $channel->delete(); - throw $e; + throw ValidationException::withMessages([ + 'provider' => $e->getMessage(), + ]); } $channel->connected = true; $channel->save(); } + /** + * @param array $input + * @return array + */ public static function rules(array $input): array { $rules = [ @@ -59,9 +66,13 @@ public static function rules(array $input): array 'label' => 'required', ]; - return array_merge($rules, static::providerRules($input)); + return array_merge($rules, self::providerRules($input)); } + /** + * @param array $input + * @return array> + */ private static function providerRules(array $input): array { if (! isset($input['provider'])) { diff --git a/app/Actions/NotificationChannels/EditChannel.php b/app/Actions/NotificationChannels/EditChannel.php index 1404930..3eb0156 100644 --- a/app/Actions/NotificationChannels/EditChannel.php +++ b/app/Actions/NotificationChannels/EditChannel.php @@ -7,6 +7,9 @@ class EditChannel { + /** + * @param array $input + */ public function edit(NotificationChannel $notificationChannel, User $user, array $input): void { $notificationChannel->fill([ @@ -16,6 +19,10 @@ public function edit(NotificationChannel $notificationChannel, User $user, array $notificationChannel->save(); } + /** + * @param array $input + * @return array + */ public static function rules(array $input): array { return [ diff --git a/app/Actions/PHP/ChangeDefaultCli.php b/app/Actions/PHP/ChangeDefaultCli.php index 79a311f..8c946f8 100644 --- a/app/Actions/PHP/ChangeDefaultCli.php +++ b/app/Actions/PHP/ChangeDefaultCli.php @@ -3,24 +3,37 @@ namespace App\Actions\PHP; use App\Enums\ServiceStatus; +use App\Exceptions\SSHError; use App\Models\Server; +use App\Models\Service; use App\SSH\Services\PHP\PHP; use Illuminate\Validation\ValidationException; class ChangeDefaultCli { + /** + * @param array $input + * + * @throws SSHError + */ public function change(Server $server, array $input): void { $this->validate($server, $input); + /** @var Service $service */ $service = $server->php($input['version']); /** @var PHP $handler */ $handler = $service->handler(); $handler->setDefaultCli(); - $server->defaultService('php')->update(['is_default' => 0]); + $server->defaultService('php')?->update(['is_default' => 0]); $service->update(['is_default' => 1]); $service->update(['status' => ServiceStatus::READY]); } + /** + * @param array $input + * + * @throws ValidationException + */ public function validate(Server $server, array $input): void { if (! isset($input['version']) || ! in_array($input['version'], $server->installedPHPVersions())) { diff --git a/app/Actions/PHP/GetPHPIni.php b/app/Actions/PHP/GetPHPIni.php index e940478..4a96768 100644 --- a/app/Actions/PHP/GetPHPIni.php +++ b/app/Actions/PHP/GetPHPIni.php @@ -4,17 +4,25 @@ use App\Enums\PHPIniType; use App\Models\Server; +use App\Models\Service; use App\SSH\Services\PHP\PHP; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; +use Throwable; class GetPHPIni { + /** + * @param array $input + * + * @throws ValidationException + */ public function getIni(Server $server, array $input): string { $this->validate($server, $input); + /** @var Service $php */ $php = $server->php($input['version']); try { @@ -22,13 +30,18 @@ public function getIni(Server $server, array $input): string $handler = $php->handler(); return $handler->getPHPIni($input['type']); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw ValidationException::withMessages( ['ini' => $e->getMessage()] ); } } + /** + * @param array $input + * + * @throws ValidationException + */ public function validate(Server $server, array $input): void { Validator::make($input, [ diff --git a/app/Actions/PHP/InstallNewPHP.php b/app/Actions/PHP/InstallNewPHP.php index cb1267c..f773702 100755 --- a/app/Actions/PHP/InstallNewPHP.php +++ b/app/Actions/PHP/InstallNewPHP.php @@ -10,6 +10,9 @@ class InstallNewPHP { + /** + * @param array $input + */ public function install(Server $server, array $input): void { $php = new Service([ @@ -26,15 +29,18 @@ public function install(Server $server, array $input): void ]); $php->save(); - dispatch(function () use ($php) { + dispatch(function () use ($php): void { $php->handler()->install(); $php->status = ServiceStatus::READY; $php->save(); - })->catch(function () use ($php) { + })->catch(function () use ($php): void { $php->delete(); })->onConnection('ssh'); } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/PHP/InstallPHPExtension.php b/app/Actions/PHP/InstallPHPExtension.php index 754aa06..3b0760e 100755 --- a/app/Actions/PHP/InstallPHPExtension.php +++ b/app/Actions/PHP/InstallPHPExtension.php @@ -2,7 +2,6 @@ namespace App\Actions\PHP; -use App\Exceptions\SSHCommandError; use App\Models\Server; use App\Models\Service; use App\SSH\Services\PHP\PHP; @@ -11,6 +10,11 @@ class InstallPHPExtension { + /** + * @param array $input + * + * @throws ValidationException + */ public function install(Server $server, array $input): Service { /** @var Service $service */ @@ -23,20 +27,17 @@ public function install(Server $server, array $input): Service } $typeData = $service->type_data; - $typeData['extensions'] = $typeData['extensions'] ?? []; + $typeData['extensions'] ??= []; $typeData['extensions'][] = $input['extension']; $service->type_data = $typeData; $service->save(); dispatch( - /** - * @throws SSHCommandError - */ - function () use ($service, $input) { + function () use ($service, $input): void { /** @var PHP $handler */ $handler = $service->handler(); $handler->installExtension($input['extension']); - })->catch(function () use ($service, $input) { + })->catch(function () use ($service, $input): void { $service->refresh(); $typeData = $service->type_data; $typeData['extensions'] = array_values(array_diff($typeData['extensions'], [$input['extension']])); @@ -47,6 +48,9 @@ function () use ($service, $input) { return $service; } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/PHP/UninstallPHP.php b/app/Actions/PHP/UninstallPHP.php index 9c7e8d5..33e0159 100755 --- a/app/Actions/PHP/UninstallPHP.php +++ b/app/Actions/PHP/UninstallPHP.php @@ -10,6 +10,11 @@ class UninstallPHP { + /** + * @param array $input + * + * @throws ValidationException + */ public function uninstall(Server $server, array $input): void { $this->validate($server, $input); @@ -19,16 +24,18 @@ public function uninstall(Server $server, array $input): void $php->status = ServiceStatus::UNINSTALLING; $php->save(); - dispatch(function () use ($php) { + dispatch(function () use ($php): void { $php->handler()->uninstall(); $php->delete(); - })->catch(function () use ($php) { + })->catch(function () use ($php): void { $php->status = ServiceStatus::FAILED; $php->save(); })->onConnection('ssh'); } /** + * @param array $input + * * @throws ValidationException */ private function validate(Server $server, array $input): void diff --git a/app/Actions/PHP/UpdatePHPIni.php b/app/Actions/PHP/UpdatePHPIni.php index 1d5521e..5d5c914 100755 --- a/app/Actions/PHP/UpdatePHPIni.php +++ b/app/Actions/PHP/UpdatePHPIni.php @@ -4,6 +4,7 @@ use App\Enums\PHPIniType; use App\Models\Server; +use App\Models\Service; use Illuminate\Filesystem\FilesystemAdapter; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; @@ -14,10 +15,13 @@ class UpdatePHPIni { /** + * @param array $input + * * @throws ValidationException */ public function update(Server $server, array $input): void { + /** @var Service $service */ $service = $server->php($input['version']); $tmpName = Str::random(10).strtotime('now'); @@ -48,6 +52,9 @@ private function deleteTempFile(string $name): void } } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/Projects/AddUser.php b/app/Actions/Projects/AddUser.php index 61ab507..01ae1fd 100644 --- a/app/Actions/Projects/AddUser.php +++ b/app/Actions/Projects/AddUser.php @@ -9,6 +9,9 @@ class AddUser { + /** + * @param array $input + */ public function add(Project $project, array $input): void { /** @var User $user */ @@ -18,13 +21,16 @@ public function add(Project $project, array $input): void $project->users()->attach($user); } + /** + * @return array> + */ public static function rules(Project $project): array { return [ 'user' => [ 'required', Rule::exists('users', 'id'), - Rule::unique('user_project', 'user_id')->where(function (Builder $query) use ($project) { + Rule::unique('user_project', 'user_id')->where(function (Builder $query) use ($project): void { $query->where('project_id', $project->id); }), ], diff --git a/app/Actions/Projects/CreateProject.php b/app/Actions/Projects/CreateProject.php index f1e6886..4fe7ba9 100644 --- a/app/Actions/Projects/CreateProject.php +++ b/app/Actions/Projects/CreateProject.php @@ -8,10 +8,13 @@ class CreateProject { + /** + * @param array $input + */ public function create(User $user, array $input): Project { if (isset($input['name'])) { - $input['name'] = strtolower($input['name']); + $input['name'] = strtolower((string) $input['name']); } $this->validate($input); @@ -27,6 +30,9 @@ public function create(User $user, array $input): Project return $project; } + /** + * @return array> + */ public static function rules(): array { return [ @@ -40,6 +46,9 @@ public static function rules(): array ]; } + /** + * @param array $input + */ private function validate(array $input): void { Validator::make($input, self::rules())->validate(); diff --git a/app/Actions/Projects/UpdateProject.php b/app/Actions/Projects/UpdateProject.php index 0cf2ae3..b8040d4 100644 --- a/app/Actions/Projects/UpdateProject.php +++ b/app/Actions/Projects/UpdateProject.php @@ -8,10 +8,13 @@ class UpdateProject { + /** + * @param array $input + */ public function update(Project $project, array $input): Project { if (isset($input['name'])) { - $input['name'] = strtolower($input['name']); + $input['name'] = strtolower((string) $input['name']); } $this->validate($project, $input); @@ -23,6 +26,9 @@ public function update(Project $project, array $input): Project return $project; } + /** + * @return array> + */ public static function rules(Project $project): array { return [ @@ -36,6 +42,9 @@ public static function rules(Project $project): array ]; } + /** + * @param array $input + */ private function validate(Project $project, array $input): void { Validator::make($input, self::rules($project))->validate(); diff --git a/app/Actions/Queue/CreateQueue.php b/app/Actions/Queue/CreateQueue.php index b908856..337b849 100644 --- a/app/Actions/Queue/CreateQueue.php +++ b/app/Actions/Queue/CreateQueue.php @@ -5,6 +5,7 @@ use App\Enums\QueueStatus; use App\Models\Queue; use App\Models\Server; +use App\Models\Service; use App\Models\Site; use App\SSH\Services\ProcessManager\ProcessManager; use Illuminate\Validation\Rule; @@ -13,6 +14,9 @@ class CreateQueue { /** + * @param Server|Site $queueable + * @param array $input + * * @throws ValidationException */ public function create(mixed $queueable, array $input): void @@ -29,9 +33,11 @@ public function create(mixed $queueable, array $input): void ]); $queue->save(); - dispatch(function () use ($queue) { + dispatch(function () use ($queue): void { + /** @var Service $service */ + $service = $queue->server->processManager(); /** @var ProcessManager $processManager */ - $processManager = $queue->server->processManager()->handler(); + $processManager = $service->handler(); $processManager->create( $queue->id, $queue->command, @@ -44,11 +50,14 @@ public function create(mixed $queueable, array $input): void ); $queue->status = QueueStatus::RUNNING; $queue->save(); - })->catch(function () use ($queue) { + })->catch(function () use ($queue): void { $queue->delete(); })->onConnection('ssh'); } + /** + * @return array> + */ public static function rules(Site $site): array { return [ diff --git a/app/Actions/Queue/EditQueue.php b/app/Actions/Queue/EditQueue.php index a035e99..624937d 100644 --- a/app/Actions/Queue/EditQueue.php +++ b/app/Actions/Queue/EditQueue.php @@ -5,6 +5,7 @@ use App\Enums\QueueStatus; use App\Models\Queue; use App\Models\Server; +use App\Models\Service; use App\SSH\Services\ProcessManager\ProcessManager; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; @@ -12,6 +13,8 @@ class EditQueue { /** + * @param array $input + * * @throws ValidationException */ public function edit(Queue $queue, array $input): void @@ -26,9 +29,11 @@ public function edit(Queue $queue, array $input): void ]); $queue->save(); - dispatch(function () use ($queue) { + dispatch(function () use ($queue): void { + /** @var Service $service */ + $service = $queue->server->processManager(); /** @var ProcessManager $processManager */ - $processManager = $queue->server->processManager()->handler(); + $processManager = $service->handler(); $processManager->delete($queue->id, $queue->site_id); $processManager->create( @@ -43,12 +48,15 @@ public function edit(Queue $queue, array $input): void ); $queue->status = QueueStatus::RUNNING; $queue->save(); - })->catch(function () use ($queue) { + })->catch(function () use ($queue): void { $queue->status = QueueStatus::FAILED; $queue->save(); })->onConnection('ssh'); } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/Queue/GetQueueLogs.php b/app/Actions/Queue/GetQueueLogs.php index bcb04d1..abd69c2 100644 --- a/app/Actions/Queue/GetQueueLogs.php +++ b/app/Actions/Queue/GetQueueLogs.php @@ -3,11 +3,19 @@ namespace App\Actions\Queue; use App\Models\Queue; +use App\Models\Service; +use App\SSH\Services\ProcessManager\ProcessManager; class GetQueueLogs { public function getLogs(Queue $queue): string { - return $queue->server->processManager()->handler()->getLogs($queue->user, $queue->getLogFile()); + /** @var Service $service */ + $service = $queue->server->processManager(); + + /** @var ProcessManager $handler */ + $handler = $service->handler(); + + return $handler->getLogs($queue->user, $queue->getLogFile()); } } diff --git a/app/Actions/Queue/ManageQueue.php b/app/Actions/Queue/ManageQueue.php index 4a89fb3..3bdef41 100644 --- a/app/Actions/Queue/ManageQueue.php +++ b/app/Actions/Queue/ManageQueue.php @@ -4,6 +4,8 @@ use App\Enums\QueueStatus; use App\Models\Queue; +use App\Models\Service; +use App\SSH\Services\ProcessManager\ProcessManager; class ManageQueue { @@ -11,8 +13,12 @@ public function start(Queue $queue): void { $queue->status = QueueStatus::STARTING; $queue->save(); - dispatch(function () use ($queue) { - $queue->server->processManager()->handler()->start($queue->id, $queue->site_id); + dispatch(function () use ($queue): void { + /** @var Service $service */ + $service = $queue->server->processManager(); + /** @var ProcessManager $handler */ + $handler = $service->handler(); + $handler->start($queue->id, $queue->site_id); $queue->status = QueueStatus::RUNNING; $queue->save(); })->onConnection('ssh'); @@ -22,8 +28,12 @@ public function stop(Queue $queue): void { $queue->status = QueueStatus::STOPPING; $queue->save(); - dispatch(function () use ($queue) { - $queue->server->processManager()->handler()->stop($queue->id, $queue->site_id); + dispatch(function () use ($queue): void { + /** @var Service $service */ + $service = $queue->server->processManager(); + /** @var ProcessManager $handler */ + $handler = $service->handler(); + $handler->stop($queue->id, $queue->site_id); $queue->status = QueueStatus::STOPPED; $queue->save(); })->onConnection('ssh'); @@ -33,8 +43,12 @@ public function restart(Queue $queue): void { $queue->status = QueueStatus::RESTARTING; $queue->save(); - dispatch(function () use ($queue) { - $queue->server->processManager()->handler()->restart($queue->id, $queue->site_id); + dispatch(function () use ($queue): void { + /** @var Service $service */ + $service = $queue->server->processManager(); + /** @var ProcessManager $handler */ + $handler = $service->handler(); + $handler->restart($queue->id, $queue->site_id); $queue->status = QueueStatus::RUNNING; $queue->save(); })->onConnection('ssh'); diff --git a/app/Actions/SSL/CreateSSL.php b/app/Actions/SSL/CreateSSL.php index 5f2392e..6048aee 100644 --- a/app/Actions/SSL/CreateSSL.php +++ b/app/Actions/SSL/CreateSSL.php @@ -5,6 +5,7 @@ use App\Enums\SslStatus; use App\Enums\SslType; use App\Models\ServerLog; +use App\Models\Service; use App\Models\Site; use App\Models\Ssl; use App\SSH\Services\Webserver\Webserver; @@ -14,6 +15,8 @@ class CreateSSL { /** + * @param array $input + * * @throws ValidationException */ public function create(Site $site, array $input): void @@ -40,19 +43,25 @@ public function create(Site $site, array $input): void $ssl->log_id = ServerLog::log($site->server, 'create-ssl', '', $site)->id; $ssl->save(); - dispatch(function () use ($site, $ssl) { + dispatch(function () use ($site, $ssl): void { + /** @var Service $service */ + $service = $site->server->webserver(); /** @var Webserver $webserver */ - $webserver = $site->server->webserver()->handler(); + $webserver = $service->handler(); $webserver->setupSSL($ssl); $ssl->status = SslStatus::CREATED; $ssl->save(); $webserver->updateVHost($site); - })->catch(function () use ($ssl) { + })->catch(function () use ($ssl): void { $ssl->status = SslStatus::FAILED; $ssl->save(); })->onConnection('ssh'); } + /** + * @param array $input + * @return array + */ public static function rules(array $input): array { $rules = [ diff --git a/app/Actions/SSL/DeleteSSL.php b/app/Actions/SSL/DeleteSSL.php index ff3e47c..a25c648 100644 --- a/app/Actions/SSL/DeleteSSL.php +++ b/app/Actions/SSL/DeleteSSL.php @@ -3,6 +3,7 @@ namespace App\Actions\SSL; use App\Enums\SslStatus; +use App\Models\Service; use App\Models\Ssl; use App\SSH\Services\Webserver\Webserver; @@ -12,8 +13,10 @@ public function delete(Ssl $ssl): void { $ssl->status = SslStatus::DELETING; $ssl->save(); + /** @var Service $service */ + $service = $ssl->site->server->webserver(); /** @var Webserver $webserver */ - $webserver = $ssl->site->server->webserver()->handler(); + $webserver = $service->handler(); $webserver->removeSSL($ssl); $ssl->delete(); } diff --git a/app/Actions/Script/CreateScript.php b/app/Actions/Script/CreateScript.php index 0734868..150620d 100644 --- a/app/Actions/Script/CreateScript.php +++ b/app/Actions/Script/CreateScript.php @@ -7,6 +7,9 @@ class CreateScript { + /** + * @param array $input + */ public function create(User $user, array $input): Script { $script = new Script([ @@ -20,6 +23,9 @@ public function create(User $user, array $input): Script return $script; } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Script/EditScript.php b/app/Actions/Script/EditScript.php index b155354..e81466f 100644 --- a/app/Actions/Script/EditScript.php +++ b/app/Actions/Script/EditScript.php @@ -7,6 +7,9 @@ class EditScript { + /** + * @param array $input + */ public function edit(Script $script, User $user, array $input): Script { $script->name = $input['name']; @@ -18,6 +21,9 @@ public function edit(Script $script, User $user, array $input): Script return $script; } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Script/ExecuteScript.php b/app/Actions/Script/ExecuteScript.php index 0740ba3..a06b1c6 100644 --- a/app/Actions/Script/ExecuteScript.php +++ b/app/Actions/Script/ExecuteScript.php @@ -11,6 +11,9 @@ class ExecuteScript { + /** + * @param array $input + */ public function execute(Script $script, array $input): ScriptExecution { $execution = new ScriptExecution([ @@ -22,16 +25,19 @@ public function execute(Script $script, array $input): ScriptExecution ]); $execution->save(); - dispatch(function () use ($execution, $script) { + dispatch(function () use ($execution, $script): void { + /** @var Server $server */ + $server = $execution->server; + $content = $execution->getContent(); - $log = ServerLog::make($execution->server, 'script-'.$script->id.'-'.strtotime('now')); + $log = ServerLog::newLog($server, 'script-'.$script->id.'-'.strtotime('now')); $log->save(); $execution->server_log_id = $log->id; $execution->save(); - $execution->server->os()->runScript('~/', $content, $log, $execution->user); + $server->os()->runScript('~/', $content, $log, $execution->user); $execution->status = ScriptExecutionStatus::COMPLETED; $execution->save(); - })->catch(function () use ($execution) { + })->catch(function () use ($execution): void { $execution->status = ScriptExecutionStatus::FAILED; $execution->save(); })->onConnection('ssh'); @@ -39,12 +45,16 @@ public function execute(Script $script, array $input): ScriptExecution return $execution; } + /** + * @param array $input + * @return array + */ public static function rules(array $input): array { $users = ['root']; if (isset($input['server'])) { - /** @var ?Server $server */ - $server = Server::query()->find($input['server']); + /** @var Server $server */ + $server = Server::query()->findOrFail($input['server']); $users = $server->getSshUsers(); } diff --git a/app/Actions/Server/CreateServer.php b/app/Actions/Server/CreateServer.php index 553c3f9..eebd2a3 100755 --- a/app/Actions/Server/CreateServer.php +++ b/app/Actions/Server/CreateServer.php @@ -24,6 +24,9 @@ class CreateServer { + /** + * @param array $input + */ public function create(User $creator, Project $project, array $input): Server { $server = new Server([ @@ -81,7 +84,7 @@ public function create(User $creator, Project $project, array $input): Server private function install(Server $server): void { - dispatch(function () use ($server) { + dispatch(function () use ($server): void { $maxWait = 180; while ($maxWait > 0) { sleep(10); @@ -102,7 +105,7 @@ private function install(Server $server): void ]); Notifier::send($server, new ServerInstallationSucceed($server)); }) - ->catch(function (Throwable $e) use ($server) { + ->catch(function (Throwable $e) use ($server): void { $server->update([ 'status' => ServerStatus::INSTALLATION_FAILED, ]); @@ -114,6 +117,10 @@ private function install(Server $server): void ->onConnection('ssh'); } + /** + * @param array $input + * @return array + */ public static function rules(Project $project, array $input): array { $rules = [ @@ -129,28 +136,22 @@ public static function rules(Project $project, array $input): array Rule::in(config('core.operating_systems')), ], 'server_provider' => [ - Rule::when(function () use ($input) { - return isset($input['provider']) && $input['provider'] != ServerProvider::CUSTOM; - }, [ + Rule::when(fn (): bool => isset($input['provider']) && $input['provider'] != ServerProvider::CUSTOM, [ 'required', - Rule::exists('server_providers', 'id')->where(function (Builder $query) use ($project) { + Rule::exists('server_providers', 'id')->where(function (Builder $query) use ($project): void { $query->where('project_id', $project->id) ->orWhereNull('project_id'); }), ]), ], 'ip' => [ - Rule::when(function () use ($input) { - return isset($input['provider']) && $input['provider'] == ServerProvider::CUSTOM; - }, [ + Rule::when(fn (): bool => isset($input['provider']) && $input['provider'] == ServerProvider::CUSTOM, [ 'required', new RestrictedIPAddressesRule, ]), ], 'port' => [ - Rule::when(function () use ($input) { - return isset($input['provider']) && $input['provider'] == ServerProvider::CUSTOM; - }, [ + Rule::when(fn (): bool => isset($input['provider']) && $input['provider'] == ServerProvider::CUSTOM, [ 'required', 'numeric', 'min:1', @@ -162,6 +163,10 @@ public static function rules(Project $project, array $input): array return array_merge($rules, self::typeRules($input), self::providerRules($input)); } + /** + * @param array $input + * @return array> + */ private static function typeRules(array $input): array { if (! isset($input['type']) || ! in_array($input['type'], config('core.server_types'))) { @@ -173,6 +178,10 @@ private static function typeRules(array $input): array return $server->type()->createRules($input); } + /** + * @param array $input + * @return array> + */ private static function providerRules(array $input): array { if ( diff --git a/app/Actions/Server/CreateServerLog.php b/app/Actions/Server/CreateServerLog.php index d973ea7..353e029 100755 --- a/app/Actions/Server/CreateServerLog.php +++ b/app/Actions/Server/CreateServerLog.php @@ -8,6 +8,8 @@ class CreateServerLog { /** + * @param array $input + * * @throws ValidationException */ public function create(Server $server, array $input): void @@ -20,6 +22,9 @@ public function create(Server $server, array $input): void ]); } + /** + * @return array + */ public static function rules(): array { return [ diff --git a/app/Actions/Server/EditServer.php b/app/Actions/Server/EditServer.php index dd7f0f5..9dbfac7 100755 --- a/app/Actions/Server/EditServer.php +++ b/app/Actions/Server/EditServer.php @@ -10,6 +10,9 @@ class EditServer { /** + * @param array $input + * @return Server $server + * * @throws ValidationException */ public function edit(Server $server, array $input): Server @@ -42,6 +45,9 @@ public function edit(Server $server, array $input): Server return $server; } + /** + * @return array> + */ public static function rules(Server $server): array { return [ diff --git a/app/Actions/Server/Update.php b/app/Actions/Server/Update.php index 818c4fd..06a08e2 100644 --- a/app/Actions/Server/Update.php +++ b/app/Actions/Server/Update.php @@ -13,11 +13,11 @@ public function update(Server $server): void { $server->status = ServerStatus::UPDATING; $server->save(); - dispatch(function () use ($server) { + dispatch(function () use ($server): void { $server->os()->upgrade(); $server->checkConnection(); $server->checkForUpdates(); - })->catch(function () use ($server) { + })->catch(function () use ($server): void { Notifier::send($server, new ServerUpdateFailed($server)); $server->checkConnection(); })->onConnection('ssh'); diff --git a/app/Actions/ServerProvider/CreateServerProvider.php b/app/Actions/ServerProvider/CreateServerProvider.php index 6b80cef..71a80c6 100644 --- a/app/Actions/ServerProvider/CreateServerProvider.php +++ b/app/Actions/ServerProvider/CreateServerProvider.php @@ -3,6 +3,7 @@ namespace App\Actions\ServerProvider; use App\Models\Project; +use App\Models\Server; use App\Models\ServerProvider; use App\Models\User; use App\ServerProviders\ServerProvider as ServerProviderContract; @@ -13,11 +14,13 @@ class CreateServerProvider { /** + * @param array $input + * * @throws ValidationException */ public function create(User $user, Project $project, array $input): ServerProvider { - $provider = static::getProvider($input['provider']); + $provider = self::getProvider($input['provider']); try { $provider->connect($input); @@ -40,13 +43,19 @@ public function create(User $user, Project $project, array $input): ServerProvid return $serverProvider; } - private static function getProvider($name): ServerProviderContract + private static function getProvider(string $name): ServerProviderContract { $providerClass = config('core.server_providers_class.'.$name); + /** @var ServerProviderContract $provider */ + $provider = new $providerClass(new ServerProvider, new Server); - return new $providerClass; + return $provider; } + /** + * @param array $input + * @return array + */ public static function rules(array $input): array { $rules = [ @@ -60,15 +69,19 @@ public static function rules(array $input): array ], ]; - return array_merge($rules, static::providerRules($input)); + return array_merge($rules, self::providerRules($input)); } + /** + * @param array $input + * @return array> + */ private static function providerRules(array $input): array { if (! isset($input['provider'])) { return []; } - return static::getProvider($input['provider'])->credentialValidationRules($input); + return self::getProvider($input['provider'])->credentialValidationRules($input); } } diff --git a/app/Actions/ServerProvider/EditServerProvider.php b/app/Actions/ServerProvider/EditServerProvider.php index 82f8947..ebd87d1 100644 --- a/app/Actions/ServerProvider/EditServerProvider.php +++ b/app/Actions/ServerProvider/EditServerProvider.php @@ -7,6 +7,9 @@ class EditServerProvider { + /** + * @param array $input + */ public function edit(ServerProvider $serverProvider, Project $project, array $input): ServerProvider { $serverProvider->profile = $input['name']; @@ -17,6 +20,9 @@ public function edit(ServerProvider $serverProvider, Project $project, array $in return $serverProvider; } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Service/Install.php b/app/Actions/Service/Install.php index 2da9dcb..b50f15d 100644 --- a/app/Actions/Service/Install.php +++ b/app/Actions/Service/Install.php @@ -10,6 +10,9 @@ class Install { + /** + * @param array $input + */ public function install(Server $server, array $input): Service { $input['type'] = config('core.service_types')[$input['name']]; @@ -28,11 +31,11 @@ public function install(Server $server, array $input): Service $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $service->handler()->install(); $service->status = ServiceStatus::READY; $service->save(); - })->catch(function () use ($service) { + })->catch(function () use ($service): void { $service->status = ServiceStatus::INSTALLATION_FAILED; $service->save(); })->onConnection('ssh'); @@ -40,6 +43,10 @@ public function install(Server $server, array $input): Service return $service; } + /** + * @param array $input + * @return array> + */ public static function rules(array $input): array { $rules = [ diff --git a/app/Actions/Service/Manage.php b/app/Actions/Service/Manage.php index 18010a3..5039133 100644 --- a/app/Actions/Service/Manage.php +++ b/app/Actions/Service/Manage.php @@ -11,7 +11,7 @@ public function start(Service $service): void { $service->status = ServiceStatus::STARTING; $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $status = $service->server->systemd()->start($service->unit); if (str($status)->contains('Active: active')) { $service->status = ServiceStatus::READY; @@ -26,7 +26,7 @@ public function stop(Service $service): void { $service->status = ServiceStatus::STOPPING; $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $status = $service->server->systemd()->stop($service->unit); if (str($status)->contains('Active: inactive')) { $service->status = ServiceStatus::STOPPED; @@ -41,7 +41,7 @@ public function restart(Service $service): void { $service->status = ServiceStatus::RESTARTING; $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $status = $service->server->systemd()->restart($service->unit); if (str($status)->contains('Active: active')) { $service->status = ServiceStatus::READY; @@ -56,7 +56,7 @@ public function enable(Service $service): void { $service->status = ServiceStatus::ENABLING; $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $status = $service->server->systemd()->enable($service->unit); if (str($status)->contains('Active: active')) { $service->status = ServiceStatus::READY; @@ -71,7 +71,7 @@ public function disable(Service $service): void { $service->status = ServiceStatus::DISABLING; $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $status = $service->server->systemd()->disable($service->unit); if (str($status)->contains('Active: inactive')) { $service->status = ServiceStatus::DISABLED; diff --git a/app/Actions/Service/Uninstall.php b/app/Actions/Service/Uninstall.php index e516e74..f3ccb8d 100644 --- a/app/Actions/Service/Uninstall.php +++ b/app/Actions/Service/Uninstall.php @@ -20,10 +20,10 @@ public function uninstall(Service $service): void $service->status = ServiceStatus::UNINSTALLING; $service->save(); - dispatch(function () use ($service) { + dispatch(function () use ($service): void { $service->handler()->uninstall(); $service->delete(); - })->catch(function () use ($service) { + })->catch(function () use ($service): void { $service->status = ServiceStatus::FAILED; $service->save(); })->onConnection('ssh'); diff --git a/app/Actions/Site/CreateCommand.php b/app/Actions/Site/CreateCommand.php index 46394ab..0a0ac6c 100644 --- a/app/Actions/Site/CreateCommand.php +++ b/app/Actions/Site/CreateCommand.php @@ -7,6 +7,9 @@ class CreateCommand { + /** + * @param array $input + */ public function create(Site $site, array $input): Command { $script = new Command([ @@ -19,6 +22,9 @@ public function create(Site $site, array $input): Command return $script; } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Site/CreateSite.php b/app/Actions/Site/CreateSite.php index 5b54c26..3b29c7d 100755 --- a/app/Actions/Site/CreateSite.php +++ b/app/Actions/Site/CreateSite.php @@ -19,6 +19,11 @@ class CreateSite { + /** + * @param array $input + * + * @throws ValidationException + */ public function create(Server $server, array $input): Site { DB::beginTransaction(); @@ -40,7 +45,7 @@ public function create(Server $server, array $input): Site // check has access to repository try { if ($site->sourceControl) { - $site->sourceControl?->getRepo($site->repository); + $site->sourceControl->getRepo($site->repository); } } catch (SourceControlIsNotConnected) { throw ValidationException::withMessages([ @@ -72,14 +77,14 @@ public function create(Server $server, array $input): Site $site->commands()->createMany($site->type()->baseCommands()); // install site - dispatch(function () use ($site) { + dispatch(function () use ($site): void { $site->type()->install(); $site->update([ 'status' => SiteStatus::READY, 'progress' => 100, ]); Notifier::send($site, new SiteInstallationSucceed($site)); - })->catch(function () use ($site) { + })->catch(function () use ($site): void { $site->status = SiteStatus::INSTALLATION_FAILED; $site->save(); Notifier::send($site, new SiteInstallationFailed($site)); @@ -96,6 +101,10 @@ public function create(Server $server, array $input): Site } } + /** + * @param array $input + * @return array + */ public static function rules(Server $server, array $input): array { $rules = [ @@ -106,9 +115,7 @@ public static function rules(Server $server, array $input): array 'domain' => [ 'required', new DomainRule, - Rule::unique('sites', 'domain')->where(function ($query) use ($server) { - return $query->where('server_id', $server->id); - }), + Rule::unique('sites', 'domain')->where(fn ($query) => $query->where('server_id', $server->id)), ], 'aliases.*' => [ new DomainRule, @@ -125,6 +132,10 @@ public static function rules(Server $server, array $input): array return array_merge($rules, self::typeRules($server, $input)); } + /** + * @param array $input + * @return array> + */ private static function typeRules(Server $server, array $input): array { if (! isset($input['type']) || ! in_array($input['type'], config('core.site_types'))) { diff --git a/app/Actions/Site/DeleteSite.php b/app/Actions/Site/DeleteSite.php index be53f51..b92c3b6 100644 --- a/app/Actions/Site/DeleteSite.php +++ b/app/Actions/Site/DeleteSite.php @@ -3,6 +3,7 @@ namespace App\Actions\Site; use App\Exceptions\SSHError; +use App\Models\Service; use App\Models\Site; use App\SSH\Services\PHP\PHP; use App\SSH\Services\Webserver\Webserver; @@ -14,13 +15,18 @@ class DeleteSite */ public function delete(Site $site): void { + /** @var Service $service */ + $service = $site->server->webserver(); + /** @var Webserver $webserverHandler */ - $webserverHandler = $site->server->webserver()->handler(); + $webserverHandler = $service->handler(); $webserverHandler->deleteSite($site); if ($site->isIsolated()) { + /** @var Service $phpService */ + $phpService = $site->server->php(); /** @var PHP $php */ - $php = $site->server->php()->handler(); + $php = $phpService->handler(); $php->removeFpmPool($site->user, $site->php_version, $site->id); $os = $site->server->os(); diff --git a/app/Actions/Site/Deploy.php b/app/Actions/Site/Deploy.php index 79fdce2..80e5151 100644 --- a/app/Actions/Site/Deploy.php +++ b/app/Actions/Site/Deploy.php @@ -39,9 +39,8 @@ public function run(Site $site): Deployment } $deployment->save(); - dispatch(function () use ($site, $deployment) { - /** @var ServerLog $log */ - $log = ServerLog::make($site->server, 'deploy-'.strtotime('now')) + dispatch(function () use ($site, $deployment): void { + $log = ServerLog::newLog($site->server, 'deploy-'.strtotime('now')) ->forSite($site); $log->save(); $deployment->log_id = $log->id; @@ -56,7 +55,7 @@ public function run(Site $site): Deployment $deployment->status = DeploymentStatus::FINISHED; $deployment->save(); Notifier::send($site, new DeploymentCompleted($deployment, $site)); - })->catch(function () use ($deployment, $site) { + })->catch(function () use ($deployment, $site): void { $deployment->status = DeploymentStatus::FAILED; $deployment->save(); Notifier::send($site, new DeploymentCompleted($deployment, $site)); diff --git a/app/Actions/Site/EditCommand.php b/app/Actions/Site/EditCommand.php index 85ae43d..6479f56 100644 --- a/app/Actions/Site/EditCommand.php +++ b/app/Actions/Site/EditCommand.php @@ -6,6 +6,9 @@ class EditCommand { + /** + * @param array $input + */ public function edit(Command $command, array $input): Command { $command->name = $input['name']; @@ -15,6 +18,9 @@ public function edit(Command $command, array $input): Command return $command; } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Site/ExecuteCommand.php b/app/Actions/Site/ExecuteCommand.php index 917bf48..2bc86ee 100644 --- a/app/Actions/Site/ExecuteCommand.php +++ b/app/Actions/Site/ExecuteCommand.php @@ -10,6 +10,9 @@ class ExecuteCommand { + /** + * @param array $input + */ public function execute(Command $command, User $user, array $input): CommandExecution { $execution = new CommandExecution([ @@ -21,22 +24,22 @@ public function execute(Command $command, User $user, array $input): CommandExec ]); $execution->save(); - dispatch(function () use ($execution, $command) { + dispatch(function () use ($execution, $command): void { $content = $execution->getContent(); - $log = ServerLog::make($execution->server, 'command-'.$command->id.'-'.strtotime('now')); + $log = ServerLog::newLog($execution->server, 'command-'.$command->id.'-'.strtotime('now')); $log->save(); $execution->server_log_id = $log->id; $execution->save(); $execution->server->os()->runScript( path: $command->site->path, script: $content, - user: $command->site->user, serverLog: $log, + user: $command->site->user, variables: $execution->variables ); $execution->status = CommandExecutionStatus::COMPLETED; $execution->save(); - })->catch(function () use ($execution) { + })->catch(function () use ($execution): void { $execution->status = CommandExecutionStatus::FAILED; $execution->save(); })->onConnection('ssh'); @@ -44,6 +47,10 @@ public function execute(Command $command, User $user, array $input): CommandExec return $execution; } + /** + * @param array $input + * @return array> + */ public static function rules(array $input): array { return [ diff --git a/app/Actions/Site/UpdateAliases.php b/app/Actions/Site/UpdateAliases.php index 3da9c86..0f2c8df 100644 --- a/app/Actions/Site/UpdateAliases.php +++ b/app/Actions/Site/UpdateAliases.php @@ -2,23 +2,33 @@ namespace App\Actions\Site; +use App\Models\Service; use App\Models\Site; use App\SSH\Services\Webserver\Webserver; use App\ValidationRules\DomainRule; class UpdateAliases { + /** + * @param array $input + */ public function update(Site $site, array $input): void { $site->aliases = $input['aliases'] ?? []; + /** @var Service $service */ + $service = $site->server->webserver(); + /** @var Webserver $webserver */ - $webserver = $site->server->webserver()->handler(); + $webserver = $service->handler(); $webserver->updateVHost($site); $site->save(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Site/UpdateBranch.php b/app/Actions/Site/UpdateBranch.php index 0e2c5dd..e66b6a9 100755 --- a/app/Actions/Site/UpdateBranch.php +++ b/app/Actions/Site/UpdateBranch.php @@ -5,12 +5,12 @@ use App\Exceptions\SSHError; use App\Models\Site; use App\SSH\Git\Git; -use Illuminate\Validation\ValidationException; class UpdateBranch { /** - * @throws ValidationException + * @param array $input + * * @throws SSHError */ public function update(Site $site, array $input): void @@ -22,7 +22,7 @@ public function update(Site $site, array $input): void } /** - * @throws ValidationException + * @return array */ public static function rules(): array { diff --git a/app/Actions/Site/UpdateDeploymentScript.php b/app/Actions/Site/UpdateDeploymentScript.php index f6c29c9..a7e91fa 100755 --- a/app/Actions/Site/UpdateDeploymentScript.php +++ b/app/Actions/Site/UpdateDeploymentScript.php @@ -2,23 +2,24 @@ namespace App\Actions\Site; +use App\Models\DeploymentScript; use App\Models\Site; -use Illuminate\Validation\ValidationException; class UpdateDeploymentScript { /** - * @throws ValidationException + * @param array $input */ public function update(Site $site, array $input): void { + /** @var DeploymentScript $script */ $script = $site->deploymentScript; $script->content = $input['script']; $script->save(); } /** - * @throws ValidationException + * @return array> */ public static function rules(): array { diff --git a/app/Actions/Site/UpdateEnv.php b/app/Actions/Site/UpdateEnv.php index fa138c8..b0b9207 100644 --- a/app/Actions/Site/UpdateEnv.php +++ b/app/Actions/Site/UpdateEnv.php @@ -8,6 +8,8 @@ class UpdateEnv { /** + * @param array $input + * * @throws SSHError */ public function update(Site $site, array $input): void @@ -15,7 +17,7 @@ public function update(Site $site, array $input): void $site->server->os()->editFileAs( $site->path.'/.env', $site->user, - trim($input['env']), + trim((string) $input['env']), ); } } diff --git a/app/Actions/Site/UpdateLoadBalancer.php b/app/Actions/Site/UpdateLoadBalancer.php index e237eb3..83cab4b 100644 --- a/app/Actions/Site/UpdateLoadBalancer.php +++ b/app/Actions/Site/UpdateLoadBalancer.php @@ -9,6 +9,9 @@ class UpdateLoadBalancer { + /** + * @param array $input + */ public function update(Site $site, array $input): void { $site->loadBalancerServers()->delete(); @@ -27,6 +30,9 @@ public function update(Site $site, array $input): void $site->webserver()->updateVHost($site); } + /** + * @return array> + */ public static function rules(Site $site): array { return [ diff --git a/app/Actions/Site/UpdatePHPVersion.php b/app/Actions/Site/UpdatePHPVersion.php index 49720d2..ed5a4f5 100644 --- a/app/Actions/Site/UpdatePHPVersion.php +++ b/app/Actions/Site/UpdatePHPVersion.php @@ -8,6 +8,9 @@ class UpdatePHPVersion { + /** + * @return array> + */ public static function rules(Site $site): array { return [ @@ -21,6 +24,8 @@ public static function rules(Site $site): array } /** + * @param array $input + * * @throws SSHError */ public function update(Site $site, array $input): void diff --git a/app/Actions/Site/UpdateSourceControl.php b/app/Actions/Site/UpdateSourceControl.php index 1506ebe..56a5b7b 100644 --- a/app/Actions/Site/UpdateSourceControl.php +++ b/app/Actions/Site/UpdateSourceControl.php @@ -11,12 +11,17 @@ class UpdateSourceControl { + /** + * @param array $input + * + * @throws ValidationException + */ public function update(Site $site, array $input): void { $site->source_control_id = $input['source_control']; try { if ($site->sourceControl) { - $site->sourceControl?->getRepo($site->repository); + $site->sourceControl->getRepo($site->repository); } } catch (SourceControlIsNotConnected) { throw ValidationException::withMessages([ @@ -34,6 +39,9 @@ public function update(Site $site, array $input): void $site->save(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/SourceControl/ConnectSourceControl.php b/app/Actions/SourceControl/ConnectSourceControl.php index 826d291..a74337d 100644 --- a/app/Actions/SourceControl/ConnectSourceControl.php +++ b/app/Actions/SourceControl/ConnectSourceControl.php @@ -4,14 +4,18 @@ use App\Models\Project; use App\Models\SourceControl; -use App\Models\User; use Illuminate\Support\Arr; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; class ConnectSourceControl { - public function connect(User $user, Project $project, array $input): SourceControl + /** + * @param array $input + * + * @throws ValidationException + */ + public function connect(Project $project, array $input): SourceControl { $sourceControl = new SourceControl([ 'provider' => $input['provider'], @@ -34,6 +38,10 @@ public function connect(User $user, Project $project, array $input): SourceContr return $sourceControl; } + /** + * @param array $input + * @return array> + */ public static function rules(array $input): array { $rules = [ @@ -46,10 +54,13 @@ public static function rules(array $input): array ], ]; - return array_merge($rules, static::providerRules($input)); + return array_merge($rules, self::providerRules($input)); } /** + * @param array $input + * @return array> + * * @throws ValidationException */ private static function providerRules(array $input): array diff --git a/app/Actions/SourceControl/EditSourceControl.php b/app/Actions/SourceControl/EditSourceControl.php index 9bde514..e6eb4f7 100644 --- a/app/Actions/SourceControl/EditSourceControl.php +++ b/app/Actions/SourceControl/EditSourceControl.php @@ -8,6 +8,11 @@ class EditSourceControl { + /** + * @param array $input + * + * @throws ValidationException + */ public function edit(SourceControl $sourceControl, Project $project, array $input): SourceControl { $sourceControl->profile = $input['name']; @@ -27,6 +32,10 @@ public function edit(SourceControl $sourceControl, Project $project, array $inpu return $sourceControl; } + /** + * @param array $input + * @return array> + */ public static function rules(SourceControl $sourceControl, array $input): array { $rules = [ @@ -35,10 +44,13 @@ public static function rules(SourceControl $sourceControl, array $input): array ], ]; - return array_merge($rules, static::providerRules($sourceControl, $input)); + return array_merge($rules, self::providerRules($sourceControl, $input)); } /** + * @param array $input + * @return array> + * * @throws ValidationException */ private static function providerRules(SourceControl $sourceControl, array $input): array diff --git a/app/Actions/SshKey/CreateSshKey.php b/app/Actions/SshKey/CreateSshKey.php index 13320f3..d21d462 100644 --- a/app/Actions/SshKey/CreateSshKey.php +++ b/app/Actions/SshKey/CreateSshKey.php @@ -10,6 +10,8 @@ class CreateSshKey { /** + * @param array $input + * * @throws ValidationException */ public function create(User $user, array $input): SshKey @@ -25,7 +27,7 @@ public function create(User $user, array $input): SshKey } /** - * @throws ValidationException + * @return array */ public static function rules(): array { diff --git a/app/Actions/SshKey/DeleteKeyFromServer.php b/app/Actions/SshKey/DeleteKeyFromServer.php index 2d28173..e382920 100644 --- a/app/Actions/SshKey/DeleteKeyFromServer.php +++ b/app/Actions/SshKey/DeleteKeyFromServer.php @@ -3,11 +3,15 @@ namespace App\Actions\SshKey; use App\Enums\SshKeyStatus; +use App\Exceptions\SSHError; use App\Models\Server; use App\Models\SshKey; class DeleteKeyFromServer { + /** + * @throws SSHError + */ public function delete(Server $server, SshKey $sshKey): void { $sshKey->servers()->updateExistingPivot($server->id, [ diff --git a/app/Actions/SshKey/DeployKeyToServer.php b/app/Actions/SshKey/DeployKeyToServer.php index 4d62063..a3b02ce 100644 --- a/app/Actions/SshKey/DeployKeyToServer.php +++ b/app/Actions/SshKey/DeployKeyToServer.php @@ -3,6 +3,7 @@ namespace App\Actions\SshKey; use App\Enums\SshKeyStatus; +use App\Exceptions\SSHError; use App\Models\Server; use App\Models\SshKey; use App\Models\User; @@ -10,6 +11,11 @@ class DeployKeyToServer { + /** + * @param array $input + * + * @throws SSHError + */ public function deploy(Server $server, array $input): void { /** @var SshKey $sshKey */ @@ -23,6 +29,9 @@ public function deploy(Server $server, array $input): void ]); } + /** + * @return array> + */ public static function rules(User $user, Server $server): array { return [ diff --git a/app/Actions/StorageProvider/CreateStorageProvider.php b/app/Actions/StorageProvider/CreateStorageProvider.php index 4c55e1b..6e9c272 100644 --- a/app/Actions/StorageProvider/CreateStorageProvider.php +++ b/app/Actions/StorageProvider/CreateStorageProvider.php @@ -11,6 +11,8 @@ class CreateStorageProvider { /** + * @param array $input + * * @throws ValidationException */ public function create(User $user, Project $project, array $input): StorageProvider @@ -41,6 +43,10 @@ public function create(User $user, Project $project, array $input): StorageProvi return $storageProvider; } + /** + * @param array $input + * @return array + */ public static function rules(array $input): array { $rules = [ diff --git a/app/Actions/StorageProvider/EditStorageProvider.php b/app/Actions/StorageProvider/EditStorageProvider.php index 824cdd4..11300ad 100644 --- a/app/Actions/StorageProvider/EditStorageProvider.php +++ b/app/Actions/StorageProvider/EditStorageProvider.php @@ -4,10 +4,12 @@ use App\Models\Project; use App\Models\StorageProvider; -use Illuminate\Validation\ValidationException; class EditStorageProvider { + /** + * @param array $input + */ public function edit(StorageProvider $storageProvider, Project $project, array $input): StorageProvider { $storageProvider->profile = $input['name']; @@ -19,7 +21,7 @@ public function edit(StorageProvider $storageProvider, Project $project, array $ } /** - * @throws ValidationException + * @return array */ public static function rules(): array { diff --git a/app/Actions/Tag/CreateTag.php b/app/Actions/Tag/CreateTag.php index 097a9a1..f666671 100644 --- a/app/Actions/Tag/CreateTag.php +++ b/app/Actions/Tag/CreateTag.php @@ -9,6 +9,11 @@ class CreateTag { + /** + * @param array $input + * + * @throws ValidationException + */ public function create(User $user, array $input): Tag { $tag = Tag::query() @@ -22,7 +27,7 @@ public function create(User $user, array $input): Tag } $tag = new Tag([ - 'project_id' => $user->currentProject->id, + 'project_id' => $user->currentProject?->id, 'name' => $input['name'], 'color' => $input['color'], ]); @@ -31,6 +36,9 @@ public function create(User $user, array $input): Tag return $tag; } + /** + * @return array + */ public static function rules(): array { return [ diff --git a/app/Actions/Tag/EditTag.php b/app/Actions/Tag/EditTag.php index 13c56cb..ed42f1d 100644 --- a/app/Actions/Tag/EditTag.php +++ b/app/Actions/Tag/EditTag.php @@ -7,6 +7,9 @@ class EditTag { + /** + * @param array $input + */ public function edit(Tag $tag, array $input): void { $tag->name = $input['name']; @@ -15,6 +18,9 @@ public function edit(Tag $tag, array $input): void $tag->save(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/Tag/SyncTags.php b/app/Actions/Tag/SyncTags.php index f66d7f3..53a52b2 100644 --- a/app/Actions/Tag/SyncTags.php +++ b/app/Actions/Tag/SyncTags.php @@ -5,12 +5,14 @@ use App\Models\Server; use App\Models\Site; use App\Models\Tag; -use App\Models\User; use Illuminate\Validation\Rule; class SyncTags { - public function sync(User $user, array $input): void + /** + * @param array $input + */ + public function sync(array $input): void { /** @var Server|Site $taggable */ $taggable = $input['taggable_type']::findOrFail($input['taggable_id']); @@ -20,6 +22,9 @@ public function sync(User $user, array $input): void $taggable->tags()->sync($tags->pluck('id')); } + /** + * @return array> + */ public static function rules(int $projectId): array { return [ diff --git a/app/Actions/User/CreateUser.php b/app/Actions/User/CreateUser.php index 7936542..55569d8 100644 --- a/app/Actions/User/CreateUser.php +++ b/app/Actions/User/CreateUser.php @@ -9,6 +9,9 @@ class CreateUser { + /** + * @param array $input + */ public function create(array $input): User { $this->validate($input); @@ -25,11 +28,17 @@ public function create(array $input): User return $user; } + /** + * @param array $input + */ private function validate(array $input): void { Validator::make($input, self::rules())->validate(); } + /** + * @return array + */ public static function rules(): array { return [ diff --git a/app/Actions/User/PasswordValidationRules.php b/app/Actions/User/PasswordValidationRules.php index aed42bb..bf5e531 100644 --- a/app/Actions/User/PasswordValidationRules.php +++ b/app/Actions/User/PasswordValidationRules.php @@ -7,9 +7,7 @@ trait PasswordValidationRules { /** - * Get the validation rules used to validate passwords. - * - * @return array + * @return array */ protected function passwordRules(): array { diff --git a/app/Actions/User/UpdateProjects.php b/app/Actions/User/UpdateProjects.php index c8bdc14..95b6520 100644 --- a/app/Actions/User/UpdateProjects.php +++ b/app/Actions/User/UpdateProjects.php @@ -5,9 +5,15 @@ use App\Models\Project; use App\Models\User; use Illuminate\Validation\Rule; +use Illuminate\Validation\ValidationException; class UpdateProjects { + /** + * @param array $input + * + * @throws ValidationException + */ public function update(User $user, array $input): void { $this->validate($input); @@ -20,7 +26,7 @@ public function update(User $user, array $input): void $user->refresh(); - /** @var Project $firstProject */ + /** @var ?Project $firstProject */ $firstProject = $user->projects->first(); if (! $user->currentProject && $firstProject) { $user->current_project_id = $firstProject->id; @@ -28,11 +34,19 @@ public function update(User $user, array $input): void } } + /** + * @param array $input + * + * @throws ValidationException + */ private function validate(array $input): void { validator($input, self::rules())->validate(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/User/UpdateUser.php b/app/Actions/User/UpdateUser.php index 70cc66b..dbd268b 100644 --- a/app/Actions/User/UpdateUser.php +++ b/app/Actions/User/UpdateUser.php @@ -9,6 +9,9 @@ class UpdateUser { + /** + * @param array $input + */ public function update(User $user, array $input): User { $this->validate($user, $input); @@ -27,11 +30,17 @@ public function update(User $user, array $input): User return $user; } + /** + * @param array $input + */ private function validate(User $user, array $input): void { Validator::make($input, self::rules($user))->validate(); } + /** + * @return array + */ public static function rules(User $user): array { return [ diff --git a/app/Actions/User/UpdateUserPassword.php b/app/Actions/User/UpdateUserPassword.php index c00e110..0274ff8 100755 --- a/app/Actions/User/UpdateUserPassword.php +++ b/app/Actions/User/UpdateUserPassword.php @@ -6,6 +6,10 @@ class UpdateUserPassword { + /** + * @param mixed $user + * @param array $input + */ public function update($user, array $input): void { $user->forceFill([ @@ -13,6 +17,9 @@ public function update($user, array $input): void ])->save(); } + /** + * @return array> + */ public static function rules(): array { return [ diff --git a/app/Actions/User/UpdateUserProfileInformation.php b/app/Actions/User/UpdateUserProfileInformation.php index b92a456..ff3808b 100755 --- a/app/Actions/User/UpdateUserProfileInformation.php +++ b/app/Actions/User/UpdateUserProfileInformation.php @@ -4,9 +4,15 @@ use App\Models\User; use Illuminate\Validation\Rule; +use Illuminate\Validation\ValidationException; class UpdateUserProfileInformation { + /** + * @param array $input + * + * @throws ValidationException + */ public function update(User $user, array $input): void { if ($input['email'] !== $user->email) { @@ -20,6 +26,9 @@ public function update(User $user, array $input): void } } + /** + * @return array> + */ public static function rules(User $user): array { return [ @@ -33,7 +42,7 @@ public static function rules(User $user): array } /** - * Update the given verified user's profile information. + * @param array $input */ protected function updateVerifiedUser(User $user, array $input): void { diff --git a/app/Console/Commands/DeleteOlderMetricsCommand.php b/app/Console/Commands/DeleteOlderMetricsCommand.php index 771610a..c570df8 100644 --- a/app/Console/Commands/DeleteOlderMetricsCommand.php +++ b/app/Console/Commands/DeleteOlderMetricsCommand.php @@ -11,10 +11,10 @@ class DeleteOlderMetricsCommand extends Command protected $description = 'Delete older metrics from database'; - public function handle() + public function handle(): void { - Service::query()->where('type', 'monitoring')->chunk(100, function ($services) { - $services->each(function ($service) { + Service::query()->where('type', 'monitoring')->chunk(100, function ($services): void { + $services->each(function ($service): void { $this->info("Deleting older metrics for service {$service->server->name}"); $service ->server diff --git a/app/Console/Commands/GetMetricsCommand.php b/app/Console/Commands/GetMetricsCommand.php index 6711ffd..0c52444 100644 --- a/app/Console/Commands/GetMetricsCommand.php +++ b/app/Console/Commands/GetMetricsCommand.php @@ -15,10 +15,10 @@ class GetMetricsCommand extends Command public function handle(): void { $checkedMetrics = 0; - Server::query()->whereHas('services', function (Builder $query) { + Server::query()->whereHas('services', function (Builder $query): void { $query->where('type', 'monitoring') ->where('name', 'remote-monitor'); - })->chunk(10, function ($servers) use (&$checkedMetrics) { + })->chunk(10, function ($servers) use (&$checkedMetrics): void { /** @var Server $server */ foreach ($servers as $server) { $info = $server->os()->resourceInfo(); diff --git a/app/Console/Commands/MigrateFromMysqlToSqlite.php b/app/Console/Commands/MigrateFromMysqlToSqlite.php index a6f3395..f64cbf4 100644 --- a/app/Console/Commands/MigrateFromMysqlToSqlite.php +++ b/app/Console/Commands/MigrateFromMysqlToSqlite.php @@ -16,9 +16,9 @@ public function handle(): void { $this->info('Migrating from Mysql to SQLite...'); - File::exists(storage_path('database.sqlite')) - ? File::delete(storage_path('database.sqlite')) - : null; + if (File::exists(storage_path('database.sqlite'))) { + File::delete(storage_path('database.sqlite')); + } File::put(storage_path('database.sqlite'), ''); diff --git a/app/Console/Commands/RunBackupCommand.php b/app/Console/Commands/RunBackupCommand.php index c6d3dfe..abe94ba 100644 --- a/app/Console/Commands/RunBackupCommand.php +++ b/app/Console/Commands/RunBackupCommand.php @@ -20,7 +20,7 @@ public function handle(): void Backup::query() ->where('interval', $this->argument('interval')) ->where('status', BackupStatus::RUNNING) - ->chunk(100, function ($backups) use (&$total) { + ->chunk(100, function ($backups) use (&$total): void { /** @var Backup $backup */ foreach ($backups as $backup) { app(RunBackup::class)->run($backup); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index e6af15c..bc70055 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -43,7 +43,7 @@ class Handler extends ExceptionHandler */ public function register(): void { - $this->reportable(function (Throwable $e) { + $this->reportable(function (Throwable $e): void { // }); } diff --git a/app/Exceptions/SSHError.php b/app/Exceptions/SSHError.php index c503a9b..5b5b711 100755 --- a/app/Exceptions/SSHError.php +++ b/app/Exceptions/SSHError.php @@ -8,12 +8,8 @@ class SSHError extends Exception { - protected ?ServerLog $log; - - public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null, ?ServerLog $log = null) + public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null, protected ?ServerLog $log = null) { - $this->log = $log; - parent::__construct($message, $code, $previous); } diff --git a/app/Facades/FTP.php b/app/Facades/FTP.php index 509af00..6ee5773 100644 --- a/app/Facades/FTP.php +++ b/app/Facades/FTP.php @@ -7,7 +7,7 @@ use Illuminate\Support\Facades\Facade; /** - * @method static bool|Connection connect(string $host, string $port, bool $ssl = false) + * @method static bool|Connection connect(string $host, int $port, bool $ssl = false) * @method static bool login(string $username, string $password, bool|Connection $connection) * @method static void close(bool|Connection $connection) * @method static bool passive(bool|Connection $connection, bool $passive) diff --git a/app/Facades/SSH.php b/app/Facades/SSH.php index 7d0cde3..2c0c57b 100644 --- a/app/Facades/SSH.php +++ b/app/Facades/SSH.php @@ -2,22 +2,20 @@ namespace App\Facades; -use App\Models\Server; -use App\Models\ServerLog; use App\Support\Testing\SSHFake; use Illuminate\Support\Facades\Facade as FacadeAlias; /** * Class SSH * - * @method static init(Server $server, string $asUser = null) - * @method static setLog(?ServerLog $log) + * @method static \App\Helpers\SSH|SSHFake init(\App\Models\Server $server, string $asUser = null) + * @method static setLog(?\App\Models\ServerLog $log) * @method static connect() * @method static string exec(string $command, string $log = '', int $siteId = null, ?bool $stream = false, callable $streamCallback = null) * @method static string upload(string $local, string $remote, ?string $owner = null) * @method static string download(string $local, string $remote) * @method static string write(string $path, string $content, string $owner = null) - * @method static string assertExecuted(array|string $commands) + * @method static string assertExecuted(array|string $commands) * @method static string assertExecutedContains(string $command) * @method static string assertFileUploaded(string $toPath, ?string $content = null) * @method static string getUploadedLocalPath() diff --git a/app/Helpers/Agent.php b/app/Helpers/Agent.php index 287961a..99eb81e 100644 --- a/app/Helpers/Agent.php +++ b/app/Helpers/Agent.php @@ -59,11 +59,9 @@ class Agent extends MobileDetect */ public function platform() { - return $this->retrieveUsingCacheOrResolve('paymently.platform', function () { - return $this->findDetectionRulesAgainstUserAgent( - $this->mergeRules(MobileDetect::getOperatingSystems(), static::$additionalOperatingSystems) - ); - }); + return $this->retrieveUsingCacheOrResolve('paymently.platform', fn () => $this->findDetectionRulesAgainstUserAgent( + $this->mergeRules(MobileDetect::getOperatingSystems(), static::$additionalOperatingSystems) + )); } /** @@ -73,11 +71,9 @@ public function platform() */ public function browser() { - return $this->retrieveUsingCacheOrResolve('paymently.browser', function () { - return $this->findDetectionRulesAgainstUserAgent( - $this->mergeRules(static::$additionalBrowsers, MobileDetect::getBrowsers()) - ); - }); + return $this->retrieveUsingCacheOrResolve('paymently.browser', fn () => $this->findDetectionRulesAgainstUserAgent( + $this->mergeRules(static::$additionalBrowsers, MobileDetect::getBrowsers()) + )); } /** @@ -87,7 +83,7 @@ public function browser() */ public function isDesktop() { - return $this->retrieveUsingCacheOrResolve('paymently.desktop', function () { + return $this->retrieveUsingCacheOrResolve('paymently.desktop', function (): bool { // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' if ( $this->getUserAgent() === static::$cloudFrontUA @@ -103,19 +99,24 @@ public function isDesktop() /** * Match a detection rule and return the matched key. * + * @param array $rules * @return string|null */ protected function findDetectionRulesAgainstUserAgent(array $rules) { $userAgent = $this->getUserAgent(); + if ($userAgent === null || $userAgent === '' || $userAgent === '0') { + return null; + } + foreach ($rules as $key => $regex) { if (empty($regex)) { continue; } if ($this->match($regex, $userAgent)) { - return $key ?: reset($this->matchesArray); + return $key !== 0 && ($key !== '' && $key !== '0') ? $key : reset($this->matchesArray); } } @@ -136,7 +137,7 @@ protected function retrieveUsingCacheOrResolve(string $key, Closure $callback) return $cacheItem; } - return tap(call_user_func($callback), function ($result) use ($cacheKey) { + return tap(call_user_func($callback), function ($result) use ($cacheKey): void { $this->store[$cacheKey] = $result; }); } @@ -144,10 +145,10 @@ protected function retrieveUsingCacheOrResolve(string $key, Closure $callback) /** * Merge multiple rules into one array. * - * @param array $all + * @param array $all * @return array */ - protected function mergeRules(...$all) + protected function mergeRules(...$all): array { $merged = []; diff --git a/app/Helpers/FTP.php b/app/Helpers/FTP.php index 1eb8a6b..241dd8c 100644 --- a/app/Helpers/FTP.php +++ b/app/Helpers/FTP.php @@ -6,7 +6,7 @@ class FTP { - public function connect(string $host, string $port, bool $ssl = false): bool|Connection + public function connect(string $host, int $port, bool $ssl = false): bool|Connection { if ($ssl) { return ftp_ssl_connect($host, $port, 5); @@ -15,22 +15,22 @@ public function connect(string $host, string $port, bool $ssl = false): bool|Con return ftp_connect($host, $port, 5); } - public function login(string $username, string $password, bool|Connection $connection): bool + public function login(string $username, string $password, Connection $connection): bool { return ftp_login($connection, $username, $password); } - public function close(bool|Connection $connection): void + public function close(Connection $connection): void { ftp_close($connection); } - public function passive(bool|Connection $connection, bool $passive): bool + public function passive(Connection $connection, bool $passive): bool { return ftp_pasv($connection, $passive); } - public function delete(bool|Connection $connection, string $path): bool + public function delete(Connection $connection, string $path): bool { return ftp_delete($connection, $path); } diff --git a/app/Helpers/SSH.php b/app/Helpers/SSH.php index db23335..18d0b44 100755 --- a/app/Helpers/SSH.php +++ b/app/Helpers/SSH.php @@ -23,13 +23,13 @@ class SSH { public Server $server; - public ?ServerLog $log; + public ?ServerLog $log = null; protected SSH2|SFTP|null $connection = null; - protected ?string $user; + protected string $user = ''; - protected ?string $asUser; + protected ?string $asUser = null; protected string $publicKey; @@ -42,11 +42,11 @@ public function init(Server $server, ?string $asUser = null): self $this->asUser = null; $this->server = $server->refresh(); $this->user = $server->getSshUser(); - if ($asUser && $asUser != $server->getSshUser()) { + if ($asUser && $asUser !== $server->getSshUser()) { $this->asUser = $asUser; } $this->privateKey = PublicKeyLoader::loadPrivateKey( - file_get_contents($this->server->sshKey()['private_key_path']) + (string) file_get_contents($this->server->sshKey()['private_key_path']) ); return $this; @@ -94,9 +94,9 @@ public function connect(bool $sftp = false): void */ public function exec(string $command, string $log = '', ?int $siteId = null, ?bool $stream = false, ?callable $streamCallback = null): string { - if (! $this->log && $log) { - $this->log = ServerLog::make($this->server, $log); - if ($siteId) { + if (! $this->log instanceof ServerLog && $log) { + $this->log = ServerLog::newLog($this->server, $log); + if ($siteId !== null && $siteId !== 0) { $this->log->forSite($siteId); } $this->log->save(); @@ -111,14 +111,15 @@ public function exec(string $command, string $log = '', ?int $siteId = null, ?bo } try { - if ($this->asUser) { + if ($this->asUser !== null && $this->asUser !== '' && $this->asUser !== '0') { $command = addslashes($command); $command = str_replace('\\\'', '\'', $command); $command = 'sudo su - '.$this->asUser.' -c '.'"'.trim($command).'"'; } $this->connection->setTimeout(0); - if ($stream) { + if ($stream === true) { + /** @var callable $streamCallback */ $this->connection->exec($command, function ($output) use ($streamCallback) { $this->log?->write($output); @@ -126,22 +127,20 @@ public function exec(string $command, string $log = '', ?int $siteId = null, ?bo }); return ''; - } else { - $output = ''; - $this->connection->exec($command, function ($out) use (&$output) { - $this->log?->write($out); - $output .= $out; - }); - - if ($this->connection->getExitStatus() !== 0 || Str::contains($output, 'VITO_SSH_ERROR')) { - throw new SSHCommandError( - message: 'SSH command failed with an error', - log: $this->log - ); - } - - return $output; } + $output = ''; + $this->connection->exec($command, function (string $out) use (&$output): void { + $this->log?->write($out); + $output .= $out; + }); + if ($this->connection->getExitStatus() !== 0 || Str::contains($output, 'VITO_SSH_ERROR')) { + throw new SSHCommandError( + message: 'SSH command failed with an error', + log: $this->log + ); + } + + return $output; } catch (Throwable $e) { Log::error('Error executing command', [ 'msg' => $e->getMessage(), @@ -168,10 +167,11 @@ public function upload(string $local, string $remote, ?string $owner = null): vo $tmpName = Str::random(10).strtotime('now'); $tempPath = home_path($this->user).'/'.$tmpName; + /** @phpstan-ignore-next-line */ $this->connection->put($tempPath, $local, SFTP::SOURCE_LOCAL_FILE); $this->exec(sprintf('sudo mv %s %s', $tempPath, $remote)); - if (! $owner) { + if ($owner === null || $owner === '' || $owner === '0') { $owner = $this->user; } $this->exec(sprintf('sudo chown %s:%s %s', $owner, $owner, $remote)); @@ -189,6 +189,7 @@ public function download(string $local, string $remote): void $this->connect(true); } + /** @phpstan-ignore-next-line */ $this->connection->get($remote, $local); } @@ -220,7 +221,7 @@ public function write(string $remotePath, string $content, ?string $owner = null */ public function disconnect(): void { - if ($this->connection) { + if ($this->connection instanceof SSH2) { $this->connection->disconnect(); $this->connection = null; } diff --git a/app/Http/Controllers/API/CronJobController.php b/app/Http/Controllers/API/CronJobController.php index d4a6b7c..8c7f013 100644 --- a/app/Http/Controllers/API/CronJobController.php +++ b/app/Http/Controllers/API/CronJobController.php @@ -73,7 +73,7 @@ public function show(Project $project, Server $server, CronJob $cronJob): CronJo #[Delete('{cronJob}', name: 'api.projects.servers.cron-jobs.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete cron job.')] #[Response(status: 204)] - public function delete(Project $project, Server $server, CronJob $cronJob) + public function delete(Project $project, Server $server, CronJob $cronJob): \Illuminate\Http\Response { $this->authorize('delete', [$cronJob, $server]); diff --git a/app/Http/Controllers/API/DatabaseController.php b/app/Http/Controllers/API/DatabaseController.php index 4deeefe..9ec54d8 100644 --- a/app/Http/Controllers/API/DatabaseController.php +++ b/app/Http/Controllers/API/DatabaseController.php @@ -72,7 +72,7 @@ public function show(Project $project, Server $server, Database $database): Data #[Delete('{database}', name: 'api.projects.servers.databases.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete database.')] #[Response(status: 204)] - public function delete(Project $project, Server $server, Database $database) + public function delete(Project $project, Server $server, Database $database): \Illuminate\Http\Response { $this->authorize('delete', [$database, $server]); diff --git a/app/Http/Controllers/API/DatabaseUserController.php b/app/Http/Controllers/API/DatabaseUserController.php index 0ed3c3d..7839a7b 100644 --- a/app/Http/Controllers/API/DatabaseUserController.php +++ b/app/Http/Controllers/API/DatabaseUserController.php @@ -90,7 +90,7 @@ public function link(Request $request, Project $project, Server $server, Databas #[Delete('{databaseUser}', name: 'api.projects.servers.database-users.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete database user.')] #[Response(status: 204)] - public function delete(Project $project, Server $server, DatabaseUser $databaseUser) + public function delete(Project $project, Server $server, DatabaseUser $databaseUser): \Illuminate\Http\Response { $this->authorize('delete', [$databaseUser, $server]); diff --git a/app/Http/Controllers/API/FirewallRuleController.php b/app/Http/Controllers/API/FirewallRuleController.php index 3220ea9..3d028f3 100644 --- a/app/Http/Controllers/API/FirewallRuleController.php +++ b/app/Http/Controllers/API/FirewallRuleController.php @@ -98,7 +98,7 @@ public function show(Project $project, Server $server, FirewallRule $firewallRul #[Delete('{firewallRule}', name: 'api.projects.servers.firewall-rules.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete firewall rule.')] #[Response(status: 204)] - public function delete(Project $project, Server $server, FirewallRule $firewallRule) + public function delete(Project $project, Server $server, FirewallRule $firewallRule): \Illuminate\Http\Response { $this->authorize('delete', [$firewallRule, $server]); diff --git a/app/Http/Controllers/API/GitHookController.php b/app/Http/Controllers/API/GitHookController.php index dde091a..21d3f3a 100644 --- a/app/Http/Controllers/API/GitHookController.php +++ b/app/Http/Controllers/API/GitHookController.php @@ -8,7 +8,9 @@ use App\Http\Controllers\Controller; use App\Models\GitHook; use App\Models\ServerLog; +use App\Models\SourceControl; use App\Notifications\SourceControlDisconnected; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Spatie\RouteAttributes\Attributes\Any; @@ -17,7 +19,7 @@ class GitHookController extends Controller { #[Any('api/git-hooks', name: 'api.git-hooks')] - public function __invoke(Request $request) + public function __invoke(Request $request): JsonResponse { if (! $request->input('secret')) { abort(404); @@ -29,7 +31,9 @@ public function __invoke(Request $request) ->firstOrFail(); foreach ($gitHook->actions as $action) { - $webhookBranch = $gitHook->site->sourceControl->provider()->getWebhookBranch($request->array()); + /** @var SourceControl $sourceControl */ + $sourceControl = $gitHook->site->sourceControl; + $webhookBranch = $sourceControl->provider()->getWebhookBranch($request->array()); if ($action == 'deploy' && $gitHook->site->branch === $webhookBranch) { try { app(Deploy::class)->run($gitHook->site); diff --git a/app/Http/Controllers/API/HealthController.php b/app/Http/Controllers/API/HealthController.php index d1e72fa..c6efe31 100644 --- a/app/Http/Controllers/API/HealthController.php +++ b/app/Http/Controllers/API/HealthController.php @@ -14,7 +14,7 @@ class HealthController extends Controller #[Get('api/health', name: 'api.health')] #[Unauthenticated] #[Endpoint(title: 'health-check')] - public function __invoke() + public function __invoke(): \Illuminate\Http\JsonResponse { return response()->json([ 'success' => true, diff --git a/app/Http/Controllers/API/ProjectController.php b/app/Http/Controllers/API/ProjectController.php index 99666fb..0a2aebe 100644 --- a/app/Http/Controllers/API/ProjectController.php +++ b/app/Http/Controllers/API/ProjectController.php @@ -45,7 +45,9 @@ public function create(Request $request): ProjectResource $this->validate($request, CreateProject::rules()); - $project = app(CreateProject::class)->create(auth()->user(), $request->all()); + /** @var \App\Models\User $user */ + $user = auth()->user(); + $project = app(CreateProject::class)->create($user, $request->all()); return new ProjectResource($project); } @@ -82,7 +84,9 @@ public function delete(Project $project): Response { $this->authorize('delete', $project); - app(DeleteProject::class)->delete(auth()->user(), $project); + /** @var \App\Models\User $user */ + $user = auth()->user(); + app(DeleteProject::class)->delete($user, $project); return response()->noContent(); } diff --git a/app/Http/Controllers/API/ServerController.php b/app/Http/Controllers/API/ServerController.php index 479a53b..920d3b1 100644 --- a/app/Http/Controllers/API/ServerController.php +++ b/app/Http/Controllers/API/ServerController.php @@ -61,7 +61,9 @@ public function create(Request $request, Project $project): ServerResource $this->validate($request, CreateServer::rules($project, $request->input())); - $server = app(CreateServer::class)->create(auth()->user(), $project, $request->all()); + /** @var \App\Models\User $user */ + $user = auth()->user(); + $server = app(CreateServer::class)->create($user, $project, $request->all()); return new ServerResource($server); } @@ -81,7 +83,7 @@ public function show(Project $project, Server $server): ServerResource #[Post('{server}/reboot', name: 'api.projects.servers.reboot', middleware: 'ability:write')] #[Endpoint(title: 'reboot', description: 'Reboot a server.')] #[Response(status: 204)] - public function reboot(Project $project, Server $server) + public function reboot(Project $project, Server $server): \Illuminate\Http\Response { $this->authorize('update', [$server, $project]); @@ -95,7 +97,7 @@ public function reboot(Project $project, Server $server) #[Post('{server}/upgrade', name: 'api.projects.servers.upgrade', middleware: 'ability:write')] #[Endpoint(title: 'upgrade', description: 'Upgrade server.')] #[Response(status: 204)] - public function upgrade(Project $project, Server $server) + public function upgrade(Project $project, Server $server): \Illuminate\Http\Response { $this->authorize('update', [$server, $project]); @@ -109,7 +111,7 @@ public function upgrade(Project $project, Server $server) #[Delete('{server}', name: 'api.projects.servers.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete server.')] #[Response(status: 204)] - public function delete(Project $project, Server $server) + public function delete(Project $project, Server $server): \Illuminate\Http\Response { $this->authorize('delete', [$server, $project]); diff --git a/app/Http/Controllers/API/ServerProviderController.php b/app/Http/Controllers/API/ServerProviderController.php index 869dc58..e9b44c4 100644 --- a/app/Http/Controllers/API/ServerProviderController.php +++ b/app/Http/Controllers/API/ServerProviderController.php @@ -54,7 +54,9 @@ public function create(Request $request, Project $project): ServerProviderResour $this->validate($request, CreateServerProvider::rules($request->all())); - $serverProvider = app(CreateServerProvider::class)->create(auth()->user(), $project, $request->all()); + /** @var \App\Models\User $user */ + $user = auth()->user(); + $serverProvider = app(CreateServerProvider::class)->create($user, $project, $request->all()); return new ServerProviderResource($serverProvider); } @@ -62,7 +64,7 @@ public function create(Request $request, Project $project): ServerProviderResour #[Get('{serverProvider}', name: 'api.projects.server-providers.show', middleware: 'ability:read')] #[Endpoint(title: 'show')] #[ResponseFromApiResource(ServerProviderResource::class, ServerProvider::class)] - public function show(Project $project, ServerProvider $serverProvider) + public function show(Project $project, ServerProvider $serverProvider): \App\Http\Resources\ServerProviderResource { $this->authorize('view', $serverProvider); @@ -76,7 +78,7 @@ public function show(Project $project, ServerProvider $serverProvider) #[BodyParam(name: 'name', description: 'The name of the server provider.', required: true)] #[BodyParam(name: 'global', description: 'Accessible in all projects', enum: [true, false])] #[ResponseFromApiResource(ServerProviderResource::class, ServerProvider::class)] - public function update(Request $request, Project $project, ServerProvider $serverProvider) + public function update(Request $request, Project $project, ServerProvider $serverProvider): \App\Http\Resources\ServerProviderResource { $this->authorize('update', $serverProvider); @@ -92,7 +94,7 @@ public function update(Request $request, Project $project, ServerProvider $serve #[Delete('{serverProvider}', name: 'api.projects.server-providers.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete')] #[Response(status: 204)] - public function delete(Project $project, ServerProvider $serverProvider) + public function delete(Project $project, ServerProvider $serverProvider): \Illuminate\Http\Response { $this->authorize('delete', $serverProvider); diff --git a/app/Http/Controllers/API/ServerSSHKeyController.php b/app/Http/Controllers/API/ServerSSHKeyController.php index 97a5219..c184e5e 100644 --- a/app/Http/Controllers/API/ServerSSHKeyController.php +++ b/app/Http/Controllers/API/ServerSSHKeyController.php @@ -52,16 +52,21 @@ public function create(Request $request, Project $project, Server $server): SshK $this->validateRoute($project, $server); + /** @var \App\Models\User $user */ + $user = auth()->user(); + $sshKey = null; if ($request->has('key_id')) { - $this->validate($request, DeployKeyToServer::rules($request->user(), $server)); + $this->validate($request, DeployKeyToServer::rules($user, $server)); - $sshKey = $request->user()->sshKeys()->findOrFail($request->key_id); + /** @var ?SshKey $sshKey */ + $sshKey = $user->sshKeys()->findOrFail($request->key_id); } if (! $sshKey) { $this->validate($request, CreateSshKey::rules()); - $sshKey = app(CreateSshKey::class)->create($request->user(), $request->all()); + /** @var SshKey $sshKey */ + $sshKey = app(CreateSshKey::class)->create($user, $request->all()); } app(DeployKeyToServer::class)->deploy($server, ['key_id' => $sshKey->id]); @@ -72,7 +77,7 @@ public function create(Request $request, Project $project, Server $server): SshK #[Delete('{sshKey}', name: 'api.projects.servers.ssh-keys.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete ssh key from server.')] #[Response(status: 204)] - public function delete(Project $project, Server $server, SshKey $sshKey) + public function delete(Project $project, Server $server, SshKey $sshKey): \Illuminate\Http\Response { $this->authorize('delete', [$sshKey, $server]); diff --git a/app/Http/Controllers/API/SiteController.php b/app/Http/Controllers/API/SiteController.php index aa20ef7..dda0bdb 100644 --- a/app/Http/Controllers/API/SiteController.php +++ b/app/Http/Controllers/API/SiteController.php @@ -84,7 +84,7 @@ public function show(Project $project, Server $server, Site $site): SiteResource #[Delete('{site}', name: 'api.projects.servers.sites.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete', description: 'Delete site.')] #[Response(status: 204)] - public function delete(Project $project, Server $server, Site $site) + public function delete(Project $project, Server $server, Site $site): \Illuminate\Http\Response { $this->authorize('delete', [$site, $server]); diff --git a/app/Http/Controllers/API/SourceControlController.php b/app/Http/Controllers/API/SourceControlController.php index 5db9345..13af708 100644 --- a/app/Http/Controllers/API/SourceControlController.php +++ b/app/Http/Controllers/API/SourceControlController.php @@ -55,7 +55,7 @@ public function create(Request $request, Project $project): SourceControlResourc $this->validate($request, ConnectSourceControl::rules($request->all())); - $sourceControl = app(ConnectSourceControl::class)->connect(auth()->user(), $project, $request->all()); + $sourceControl = app(ConnectSourceControl::class)->connect($project, $request->all()); return new SourceControlResource($sourceControl); } @@ -63,7 +63,7 @@ public function create(Request $request, Project $project): SourceControlResourc #[Get('{sourceControl}', name: 'api.projects.source-controls.show', middleware: 'ability:read')] #[Endpoint(title: 'show')] #[ResponseFromApiResource(SourceControlResource::class, SourceControl::class)] - public function show(Project $project, SourceControl $sourceControl) + public function show(Project $project, SourceControl $sourceControl): \App\Http\Resources\SourceControlResource { $this->authorize('view', $sourceControl); @@ -81,7 +81,7 @@ public function show(Project $project, SourceControl $sourceControl) #[BodyParam(name: 'password', description: 'The password if the provider is Bitbucket')] #[BodyParam(name: 'global', description: 'Accessible in all projects', enum: [true, false])] #[ResponseFromApiResource(SourceControlResource::class, SourceControl::class)] - public function update(Request $request, Project $project, SourceControl $sourceControl) + public function update(Request $request, Project $project, SourceControl $sourceControl): \App\Http\Resources\SourceControlResource { $this->authorize('update', $sourceControl); @@ -97,7 +97,7 @@ public function update(Request $request, Project $project, SourceControl $source #[Delete('{sourceControl}', name: 'api.projects.source-controls.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete')] #[Response(status: 204)] - public function delete(Project $project, SourceControl $sourceControl) + public function delete(Project $project, SourceControl $sourceControl): \Illuminate\Http\Response { $this->authorize('delete', $sourceControl); diff --git a/app/Http/Controllers/API/StorageProviderController.php b/app/Http/Controllers/API/StorageProviderController.php index 96ac92e..5dd2f27 100644 --- a/app/Http/Controllers/API/StorageProviderController.php +++ b/app/Http/Controllers/API/StorageProviderController.php @@ -54,7 +54,9 @@ public function create(Request $request, Project $project): StorageProviderResou $this->validate($request, CreateStorageProvider::rules($request->all())); - $storageProvider = app(CreateStorageProvider::class)->create(auth()->user(), $project, $request->all()); + /** @var \App\Models\User $user */ + $user = auth()->user(); + $storageProvider = app(CreateStorageProvider::class)->create($user, $project, $request->all()); return new StorageProviderResource($storageProvider); } @@ -62,7 +64,7 @@ public function create(Request $request, Project $project): StorageProviderResou #[Get('{storageProvider}', name: 'api.projects.storage-providers.show', middleware: 'ability:read')] #[Endpoint(title: 'show')] #[ResponseFromApiResource(StorageProviderResource::class, StorageProvider::class)] - public function show(Project $project, StorageProvider $storageProvider) + public function show(Project $project, StorageProvider $storageProvider): \App\Http\Resources\StorageProviderResource { $this->authorize('view', $storageProvider); @@ -76,7 +78,7 @@ public function show(Project $project, StorageProvider $storageProvider) #[BodyParam(name: 'name', description: 'The name of the storage provider.', required: true)] #[BodyParam(name: 'global', description: 'Accessible in all projects', enum: [true, false])] #[ResponseFromApiResource(StorageProviderResource::class, StorageProvider::class)] - public function update(Request $request, Project $project, StorageProvider $storageProvider) + public function update(Request $request, Project $project, StorageProvider $storageProvider): \App\Http\Resources\StorageProviderResource { $this->authorize('update', $storageProvider); @@ -92,7 +94,7 @@ public function update(Request $request, Project $project, StorageProvider $stor #[Delete('{storageProvider}', name: 'api.projects.storage-providers.delete', middleware: 'ability:write')] #[Endpoint(title: 'delete')] #[Response(status: 204)] - public function delete(Project $project, StorageProvider $storageProvider) + public function delete(Project $project, StorageProvider $storageProvider): \Illuminate\Http\Response { $this->authorize('delete', $storageProvider); diff --git a/app/Http/Controllers/ConsoleController.php b/app/Http/Controllers/ConsoleController.php index 02c757d..510a1fd 100644 --- a/app/Http/Controllers/ConsoleController.php +++ b/app/Http/Controllers/ConsoleController.php @@ -3,18 +3,20 @@ namespace App\Http\Controllers; use App\Models\Server; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Validation\Rule; use Spatie\RouteAttributes\Attributes\Get; use Spatie\RouteAttributes\Attributes\Middleware; use Spatie\RouteAttributes\Attributes\Post; +use Symfony\Component\HttpFoundation\StreamedResponse; #[Middleware('auth')] class ConsoleController extends Controller { #[Post('servers/{server}/console/run', name: 'servers.console.run')] - public function run(Server $server, Request $request) + public function run(Server $server, Request $request): StreamedResponse { $this->authorize('update', $server); @@ -36,10 +38,10 @@ public function run(Server $server, Request $request) } return response()->stream( - function () use ($server, $request, $ssh, $log, $currentDir) { + function () use ($server, $request, $ssh, $log, $currentDir): void { $command = 'cd '.$currentDir.' && '.$request->command.' && echo -n "VITO_WORKING_DIR: " && pwd'; $output = ''; - $ssh->exec(command: $command, log: $log, stream: true, streamCallback: function ($out) use (&$output) { + $ssh->exec(command: $command, log: $log, stream: true, streamCallback: function (string $out) use (&$output): void { echo preg_replace('/^VITO_WORKING_DIR:.*(\r?\n)?/m', '', $out); $output .= $out; ob_flush(); @@ -60,7 +62,7 @@ function () use ($server, $request, $ssh, $log, $currentDir) { } #[Get('servers/{server}/console/working-dir', name: 'servers.console.working-dir')] - public function workingDir(Server $server) + public function workingDir(Server $server): JsonResponse { return response()->json([ 'dir' => Cache::get('console.'.$server->id.'.dir', '~'), diff --git a/app/Http/Middleware/CanSeeProjectMiddleware.php b/app/Http/Middleware/CanSeeProjectMiddleware.php index b51cacb..9806099 100644 --- a/app/Http/Middleware/CanSeeProjectMiddleware.php +++ b/app/Http/Middleware/CanSeeProjectMiddleware.php @@ -9,6 +9,9 @@ class CanSeeProjectMiddleware { + /** + * @return mixed + */ public function handle(Request $request, Closure $next) { /** @var User $user */ diff --git a/app/Http/Middleware/HasProjectMiddleware.php b/app/Http/Middleware/HasProjectMiddleware.php index 65b911e..9ec09df 100644 --- a/app/Http/Middleware/HasProjectMiddleware.php +++ b/app/Http/Middleware/HasProjectMiddleware.php @@ -8,6 +8,9 @@ class HasProjectMiddleware { + /** + * @return mixed + */ public function handle(Request $request, Closure $next) { /** @var ?User $user */ @@ -18,10 +21,12 @@ public function handle(Request $request, Closure $next) if (! $user->currentProject) { if ($user->allProjects()->count() > 0) { - $user->current_project_id = $user->allProjects()->first()->id; + /** @var \App\Models\Project $firstProject */ + $firstProject = $user->allProjects()->first(); + $user->current_project_id = $firstProject->id; $user->save(); - $request->user()->refresh(); + $user->refresh(); return $next($request); } diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index afc78c4..fef34bd 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -17,7 +17,7 @@ class RedirectIfAuthenticated */ public function handle(Request $request, Closure $next, string ...$guards): Response { - $guards = empty($guards) ? [null] : $guards; + $guards = $guards === [] ? [null] : $guards; foreach ($guards as $guard) { if (Auth::guard($guard)->check()) { diff --git a/app/Http/Resources/CronJobResource.php b/app/Http/Resources/CronJobResource.php index 6a923f7..d2ad527 100644 --- a/app/Http/Resources/CronJobResource.php +++ b/app/Http/Resources/CronJobResource.php @@ -9,6 +9,9 @@ /** @mixin CronJob */ class CronJobResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/DatabaseResource.php b/app/Http/Resources/DatabaseResource.php index 489d125..fefb381 100644 --- a/app/Http/Resources/DatabaseResource.php +++ b/app/Http/Resources/DatabaseResource.php @@ -9,6 +9,9 @@ /** @mixin Database */ class DatabaseResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/DatabaseUserResource.php b/app/Http/Resources/DatabaseUserResource.php index 050cc94..651f7cd 100644 --- a/app/Http/Resources/DatabaseUserResource.php +++ b/app/Http/Resources/DatabaseUserResource.php @@ -9,6 +9,9 @@ /** @mixin DatabaseUser */ class DatabaseUserResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/FirewallRuleResource.php b/app/Http/Resources/FirewallRuleResource.php index 15bc321..ef3b88a 100644 --- a/app/Http/Resources/FirewallRuleResource.php +++ b/app/Http/Resources/FirewallRuleResource.php @@ -9,6 +9,9 @@ /** @mixin FirewallRule */ class FirewallRuleResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/ProjectResource.php b/app/Http/Resources/ProjectResource.php index e7e2e9e..b82c73f 100644 --- a/app/Http/Resources/ProjectResource.php +++ b/app/Http/Resources/ProjectResource.php @@ -9,6 +9,9 @@ /** @mixin Project */ class ProjectResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/ServerProviderResource.php b/app/Http/Resources/ServerProviderResource.php index f515ae9..22e2509 100644 --- a/app/Http/Resources/ServerProviderResource.php +++ b/app/Http/Resources/ServerProviderResource.php @@ -9,6 +9,9 @@ /** @mixin ServerProvider */ class ServerProviderResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/ServerResource.php b/app/Http/Resources/ServerResource.php index b918788..06f536f 100644 --- a/app/Http/Resources/ServerResource.php +++ b/app/Http/Resources/ServerResource.php @@ -9,6 +9,9 @@ /** @mixin Server */ class ServerResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/ServiceResource.php b/app/Http/Resources/ServiceResource.php index d7e7570..39c3cab 100644 --- a/app/Http/Resources/ServiceResource.php +++ b/app/Http/Resources/ServiceResource.php @@ -9,6 +9,9 @@ /** @mixin Service */ class ServiceResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/SiteResource.php b/app/Http/Resources/SiteResource.php index 22a48bb..59dee00 100644 --- a/app/Http/Resources/SiteResource.php +++ b/app/Http/Resources/SiteResource.php @@ -9,6 +9,9 @@ /** @mixin Site */ class SiteResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/SourceControlResource.php b/app/Http/Resources/SourceControlResource.php index b3826a0..70ab0d1 100644 --- a/app/Http/Resources/SourceControlResource.php +++ b/app/Http/Resources/SourceControlResource.php @@ -9,6 +9,9 @@ /** @mixin SourceControl */ class SourceControlResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/SshKeyResource.php b/app/Http/Resources/SshKeyResource.php index 1b2fbf9..a1ae9eb 100644 --- a/app/Http/Resources/SshKeyResource.php +++ b/app/Http/Resources/SshKeyResource.php @@ -9,6 +9,9 @@ /** @mixin SshKey */ class SshKeyResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/StorageProviderResource.php b/app/Http/Resources/StorageProviderResource.php index 55973f5..07bbb94 100644 --- a/app/Http/Resources/StorageProviderResource.php +++ b/app/Http/Resources/StorageProviderResource.php @@ -9,6 +9,9 @@ /** @mixin StorageProvider */ class StorageProviderResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Http/Resources/UserResource.php b/app/Http/Resources/UserResource.php index 430c6ee..190fb29 100644 --- a/app/Http/Resources/UserResource.php +++ b/app/Http/Resources/UserResource.php @@ -9,6 +9,9 @@ /** @mixin User */ class UserResource extends JsonResource { + /** + * @return array + */ public function toArray(Request $request): array { return [ diff --git a/app/Models/Backup.php b/app/Models/Backup.php index 2f6b1ec..2ab942d 100644 --- a/app/Models/Backup.php +++ b/app/Models/Backup.php @@ -23,6 +23,7 @@ */ class Backup extends AbstractModel { + /** @use HasFactory<\Database\Factories\BackupFactory> */ use HasFactory; protected $fillable = [ @@ -46,13 +47,18 @@ public static function boot(): void { parent::boot(); - static::deleting(function (Backup $backup) { - $backup->files()->each(function (BackupFile $file) { + static::deleting(function ($backup): void { + /** @var Backup $backup */ + $backup->files()->each(function ($file): void { + /** @var BackupFile $file */ $file->delete(); }); }); } + /** + * @var array + */ public static array $statusColors = [ BackupStatus::RUNNING => 'success', BackupStatus::FAILED => 'danger', @@ -62,31 +68,46 @@ public static function boot(): void public function isCustomInterval(): bool { $intervals = array_keys(config('core.cronjob_intervals')); - $intervals = array_filter($intervals, fn ($interval) => $interval !== 'custom'); + $intervals = array_filter($intervals, fn ($interval): bool => $interval !== 'custom'); return ! in_array($this->interval, $intervals); } + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } + /** + * @return BelongsTo + */ public function storage(): BelongsTo { return $this->belongsTo(StorageProvider::class, 'storage_id'); } + /** + * @return BelongsTo + */ public function database(): BelongsTo { return $this->belongsTo(Database::class)->withTrashed(); } + /** + * @return HasMany + */ public function files(): HasMany { return $this->hasMany(BackupFile::class, 'backup_id'); } + /** + * @return HasOne + */ public function lastFile(): HasOne { return $this->hasOne(BackupFile::class, 'backup_id')->latest(); diff --git a/app/Models/BackupFile.php b/app/Models/BackupFile.php index 7a177f2..600a654 100644 --- a/app/Models/BackupFile.php +++ b/app/Models/BackupFile.php @@ -20,6 +20,7 @@ */ class BackupFile extends AbstractModel { + /** @use HasFactory<\Database\Factories\BackupFileFactory> */ use HasFactory; protected $fillable = [ @@ -38,15 +39,16 @@ class BackupFile extends AbstractModel protected static function booted(): void { - static::created(function (BackupFile $backupFile) { + static::created(function (BackupFile $backupFile): void { $keep = $backupFile->backup->keep_backups; if ($backupFile->backup->files()->count() > $keep) { - /* @var BackupFile $lastFileToKeep */ + /** @var ?BackupFile $lastFileToKeep */ $lastFileToKeep = $backupFile->backup->files()->orderByDesc('id')->skip($keep)->first(); if ($lastFileToKeep) { $files = $backupFile->backup->files() ->where('id', '<=', $lastFileToKeep->id) ->get(); + /** @var BackupFile $file */ foreach ($files as $file) { app(ManageBackupFile::class)->delete($file); } @@ -55,6 +57,9 @@ protected static function booted(): void }); } + /** + * @var array + */ public static array $statusColors = [ BackupFileStatus::CREATED => 'success', BackupFileStatus::CREATING => 'warning', @@ -78,6 +83,9 @@ public function isLocal(): bool return $this->backup->storage->provider === StorageProviderAlias::LOCAL; } + /** + * @return BelongsTo + */ public function backup(): BelongsTo { return $this->belongsTo(Backup::class); @@ -96,7 +104,7 @@ public function path(): string return match ($storage->provider) { StorageProviderAlias::DROPBOX => '/'.$databaseName.'/'.$this->name.'.zip', StorageProviderAlias::S3, StorageProviderAlias::FTP, StorageProviderAlias::LOCAL => implode('/', [ - rtrim($storage->credentials['path'], '/'), + rtrim((string) $storage->credentials['path'], '/'), $databaseName, $this->name.'.zip', ]), diff --git a/app/Models/Command.php b/app/Models/Command.php index dd850f1..b28fabf 100644 --- a/app/Models/Command.php +++ b/app/Models/Command.php @@ -16,12 +16,13 @@ * @property string $command * @property Carbon $created_at * @property Carbon $updated_at - * @property Collection $executions + * @property Collection $executions * @property ?CommandExecution $lastExecution * @property Site $site */ class Command extends AbstractModel { + /** @use HasFactory<\Database\Factories\CommandFactory> */ use HasFactory; protected $fillable = [ @@ -38,32 +39,42 @@ public static function boot(): void { parent::boot(); - static::deleting(function (Command $command) { + static::deleting(function (Command $command): void { $command->executions()->delete(); }); } + /** + * @return BelongsTo + */ public function site(): BelongsTo { return $this->belongsTo(Site::class); } + /** + * @return array + */ public function getVariables(): array { $variables = []; preg_match_all('/\${(.*?)}/', $this->command, $matches); - foreach ($matches[1] as $match) { - $variables[] = $match; - } + $variables = $matches[1]; return array_unique($variables); } + /** + * @return HasMany + */ public function executions(): HasMany { return $this->hasMany(CommandExecution::class); } + /** + * @return HasOne + */ public function lastExecution(): HasOne { return $this->hasOne(CommandExecution::class)->latest(); diff --git a/app/Models/CommandExecution.php b/app/Models/CommandExecution.php index ea3e613..e02ee7b 100644 --- a/app/Models/CommandExecution.php +++ b/app/Models/CommandExecution.php @@ -13,7 +13,7 @@ * @property int $server_id * @property int $user_id * @property ?int $server_log_id - * @property array $variables + * @property array $variables * @property string $status * @property Carbon $created_at * @property Carbon $updated_at @@ -24,6 +24,7 @@ */ class CommandExecution extends AbstractModel { + /** @use HasFactory<\Database\Factories\CommandExecutionFactory> */ use HasFactory; protected $fillable = [ @@ -43,12 +44,18 @@ class CommandExecution extends AbstractModel 'variables' => 'array', ]; + /** + * @var array + */ public static array $statusColors = [ CommandExecutionStatus::EXECUTING => 'warning', CommandExecutionStatus::COMPLETED => 'success', CommandExecutionStatus::FAILED => 'danger', ]; + /** + * @return BelongsTo + */ public function command(): BelongsTo { return $this->belongsTo(Command::class); @@ -58,7 +65,7 @@ public function getContent(): string { $content = $this->command->command; foreach ($this->variables as $variable => $value) { - if (is_string($value) && ! empty($value)) { + if (is_string($value) && ($value !== '' && $value !== '0')) { $content = str_replace('${'.$variable.'}', $value, $content); } } @@ -66,16 +73,25 @@ public function getContent(): string return $content; } + /** + * @return BelongsTo + */ public function serverLog(): BelongsTo { return $this->belongsTo(ServerLog::class); } + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } + /** + * @return BelongsTo + */ public function user(): BelongsTo { return $this->belongsTo(User::class); diff --git a/app/Models/CronJob.php b/app/Models/CronJob.php index c076a3d..ef6e8cd 100755 --- a/app/Models/CronJob.php +++ b/app/Models/CronJob.php @@ -18,6 +18,7 @@ */ class CronJob extends AbstractModel { + /** @use HasFactory<\Database\Factories\CronJobFactory> */ use HasFactory; protected $fillable = [ @@ -34,6 +35,9 @@ class CronJob extends AbstractModel 'hidden' => 'boolean', ]; + /** + * @var array + */ public static array $statusColors = [ CronjobStatus::CREATING => 'warning', CronjobStatus::READY => 'success', @@ -43,6 +47,9 @@ class CronJob extends AbstractModel CronjobStatus::DISABLED => 'gray', ]; + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); @@ -59,6 +66,7 @@ public static function crontab(Server $server, string $user): string CronjobStatus::ENABLING, ]) ->get(); + /** @var CronJob $cronJob */ foreach ($cronJobs as $key => $cronJob) { $data .= $cronJob->frequency.' '.$cronJob->command; if ($key != count($cronJobs) - 1) { @@ -78,11 +86,8 @@ public function frequencyLabel(): string '0 0 * * 0' => 'Weekly', '0 0 1 * *' => 'Monthly', ]; - if (isset($labels[$this->frequency])) { - return $labels[$this->frequency]; - } - return $this->frequency; + return $labels[$this->frequency] ?? $this->frequency; } public function isEnabled(): bool diff --git a/app/Models/Database.php b/app/Models/Database.php index b319f52..e221a92 100755 --- a/app/Models/Database.php +++ b/app/Models/Database.php @@ -21,7 +21,9 @@ */ class Database extends AbstractModel { + /** @use HasFactory<\Database\Factories\DatabaseFactory> */ use HasFactory; + use SoftDeletes; protected $fillable = [ @@ -40,8 +42,9 @@ public static function boot(): void { parent::boot(); - static::deleting(function (Database $database) { - $database->server->databaseUsers()->each(function (DatabaseUser $user) use ($database) { + static::deleting(function (Database $database): void { + $database->server->databaseUsers()->each(function ($user) use ($database): void { + /** @var DatabaseUser $user */ $databases = $user->databases; if ($databases && in_array($database->name, $databases)) { unset($databases[array_search($database->name, $databases)]); @@ -52,6 +55,9 @@ public static function boot(): void }); } + /** + * @var array + */ public static array $statusColors = [ DatabaseStatus::READY => 'success', DatabaseStatus::CREATING => 'warning', @@ -59,11 +65,17 @@ public static function boot(): void DatabaseStatus::FAILED => 'danger', ]; + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } + /** + * @return HasMany + */ public function backups(): HasMany { return $this->hasMany(Backup::class)->where('type', 'database'); diff --git a/app/Models/DatabaseUser.php b/app/Models/DatabaseUser.php index 652e4f1..4af54fa 100755 --- a/app/Models/DatabaseUser.php +++ b/app/Models/DatabaseUser.php @@ -10,13 +10,14 @@ * @property int $server_id * @property string $username * @property string $password - * @property array $databases + * @property array $databases * @property string $host * @property string $status * @property Server $server */ class DatabaseUser extends AbstractModel { + /** @use HasFactory<\Database\Factories\DatabaseUserFactory> */ use HasFactory; protected $fillable = [ @@ -38,11 +39,17 @@ class DatabaseUser extends AbstractModel 'password', ]; + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } + /** + * @var array + */ public static array $statusColors = [ DatabaseUserStatus::READY => 'success', DatabaseUserStatus::CREATING => 'warning', diff --git a/app/Models/Deployment.php b/app/Models/Deployment.php index 41d6493..bcdfcf9 100755 --- a/app/Models/Deployment.php +++ b/app/Models/Deployment.php @@ -12,14 +12,15 @@ * @property int $log_id * @property string $commit_id * @property string $commit_id_short - * @property array $commit_data + * @property array $commit_data * @property string $status * @property Site $site * @property DeploymentScript $deploymentScript - * @property ServerLog $log + * @property ?ServerLog $log */ class Deployment extends AbstractModel { + /** @use HasFactory<\Database\Factories\DeploymentFactory> */ use HasFactory; protected $fillable = [ @@ -38,22 +39,34 @@ class Deployment extends AbstractModel 'commit_data' => 'json', ]; + /** + * @var array + */ public static array $statusColors = [ DeploymentStatus::DEPLOYING => 'warning', DeploymentStatus::FINISHED => 'success', DeploymentStatus::FAILED => 'danger', ]; + /** + * @return BelongsTo + */ public function site(): BelongsTo { return $this->belongsTo(Site::class); } + /** + * @return BelongsTo + */ public function deploymentScript(): BelongsTo { return $this->belongsTo(DeploymentScript::class); } + /** + * @return BelongsTo + */ public function log(): BelongsTo { return $this->belongsTo(ServerLog::class, 'log_id'); diff --git a/app/Models/DeploymentScript.php b/app/Models/DeploymentScript.php index d47b074..68fc18d 100644 --- a/app/Models/DeploymentScript.php +++ b/app/Models/DeploymentScript.php @@ -13,13 +13,14 @@ */ class DeploymentScript extends AbstractModel { + /** @use HasFactory<\Database\Factories\DeploymentScriptFactory> */ use HasFactory; protected static function boot(): void { parent::boot(); - static::saving(function ($deploymentScript) { + static::saving(function ($deploymentScript): void { $deploymentScript->content = str_replace("\r\n", "\n", $deploymentScript->content); }); } @@ -34,6 +35,9 @@ protected static function boot(): void 'site_id' => 'integer', ]; + /** + * @return BelongsTo + */ public function site(): BelongsTo { return $this->belongsTo(Site::class); diff --git a/app/Models/File.php b/app/Models/File.php index 31c6c37..34b57d3 100644 --- a/app/Models/File.php +++ b/app/Models/File.php @@ -23,6 +23,7 @@ */ class File extends AbstractModel { + /** @use HasFactory<\Database\Factories\FileFactory> */ use HasFactory; protected $fillable = [ @@ -53,7 +54,7 @@ protected static function boot(): void { parent::boot(); - static::deleting(function (File $file) { + static::deleting(function (File $file): bool { if ($file->name === '.' || $file->name === '..') { return false; } @@ -64,11 +65,17 @@ protected static function boot(): void }); } + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } + /** + * @return BelongsTo + */ public function user(): BelongsTo { return $this->belongsTo(User::class); diff --git a/app/Models/FirewallRule.php b/app/Models/FirewallRule.php index b5a5669..c7e80e1 100755 --- a/app/Models/FirewallRule.php +++ b/app/Models/FirewallRule.php @@ -20,6 +20,7 @@ */ class FirewallRule extends AbstractModel { + /** @use HasFactory<\Database\Factories\FirewallRuleFactory> */ use HasFactory; protected $fillable = [ @@ -47,9 +48,13 @@ public function getStatusColor(): string FirewallRuleStatus::DELETING => 'warning', FirewallRuleStatus::READY => 'success', FirewallRuleStatus::FAILED => 'danger', + default => 'secondary', }; } + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); diff --git a/app/Models/GitHook.php b/app/Models/GitHook.php index fd54f56..ffca9ab 100755 --- a/app/Models/GitHook.php +++ b/app/Models/GitHook.php @@ -10,15 +10,16 @@ * @property int $site_id * @property int $source_control_id * @property string $secret - * @property array $events - * @property array $actions + * @property array $events + * @property array $actions * @property string $hook_id - * @property array $hook_response + * @property array $hook_response * @property Site $site * @property SourceControl $sourceControl */ class GitHook extends AbstractModel { + /** @use HasFactory<\Database\Factories\GitHookFactory> */ use HasFactory; protected $fillable = [ @@ -39,11 +40,17 @@ class GitHook extends AbstractModel 'hook_response' => 'json', ]; + /** + * @return BelongsTo + */ public function site(): BelongsTo { return $this->belongsTo(Site::class); } + /** + * @return BelongsTo + */ public function sourceControl(): BelongsTo { return $this->belongsTo(SourceControl::class); diff --git a/app/Models/LoadBalancerServer.php b/app/Models/LoadBalancerServer.php index 30076f6..1a99953 100644 --- a/app/Models/LoadBalancerServer.php +++ b/app/Models/LoadBalancerServer.php @@ -15,6 +15,7 @@ */ class LoadBalancerServer extends AbstractModel { + /** @use HasFactory<\Database\Factories\LoadBalancerServerFactory> */ use HasFactory; protected $fillable = [ @@ -32,6 +33,9 @@ class LoadBalancerServer extends AbstractModel 'backup' => 'boolean', ]; + /** + * @return BelongsTo + */ public function loadBalancer(): BelongsTo { return $this->belongsTo(Site::class, 'load_balancer_id'); @@ -39,6 +43,9 @@ public function loadBalancer(): BelongsTo public function server(): ?Server { - return $this->loadBalancer->project->servers()->where('local_ip', $this->ip)->first(); + /** @var ?Server $server */ + $server = $this->loadBalancer->project->servers()->where('local_ip', $this->ip)->first(); + + return $server; } } diff --git a/app/Models/Metric.php b/app/Models/Metric.php index 7802b05..7c65988 100644 --- a/app/Models/Metric.php +++ b/app/Models/Metric.php @@ -10,13 +10,13 @@ /** * @property int $id * @property int $server_id - * @property float $load - * @property float $memory_total - * @property float $memory_used - * @property float $memory_free - * @property float $disk_total - * @property float $disk_used - * @property float $disk_free + * @property ?float $load + * @property ?float $memory_total + * @property ?float $memory_used + * @property ?float $memory_free + * @property ?float $disk_total + * @property ?float $disk_used + * @property ?float $disk_free * @property-read float|int $memory_total_in_bytes * @property-read float|int $memory_used_in_bytes * @property-read float|int $memory_free_in_bytes @@ -29,6 +29,7 @@ */ class Metric extends Model { + /** @use HasFactory<\Database\Factories\MetricFactory> */ use HasFactory; protected $fillable = [ @@ -53,6 +54,9 @@ class Metric extends Model 'disk_free' => 'float', ]; + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); @@ -60,31 +64,31 @@ public function server(): BelongsTo public function getMemoryTotalInBytesAttribute(): float|int { - return $this->memory_total * 1024; + return ($this->memory_total ?? 0) * 1024; } public function getMemoryUsedInBytesAttribute(): float|int { - return $this->memory_used * 1024; + return ($this->memory_used ?? 0) * 1024; } public function getMemoryFreeInBytesAttribute(): float|int { - return $this->memory_free * 1024; + return ($this->memory_free ?? 0) * 1024; } public function getDiskTotalInBytesAttribute(): float|int { - return $this->disk_total * (1024 * 1024); + return ($this->disk_total ?? 0) * (1024 * 1024); } public function getDiskUsedInBytesAttribute(): float|int { - return $this->disk_used * (1024 * 1024); + return ($this->disk_used ?? 0) * (1024 * 1024); } public function getDiskFreeInBytesAttribute(): float|int { - return $this->disk_free * (1024 * 1024); + return ($this->disk_free ?? 0) * (1024 * 1024); } } diff --git a/app/Models/NotificationChannel.php b/app/Models/NotificationChannel.php index 7305402..414e1c9 100644 --- a/app/Models/NotificationChannel.php +++ b/app/Models/NotificationChannel.php @@ -10,15 +10,17 @@ /** * @property int $id - * @property string provider - * @property array data - * @property string label - * @property bool connected + * @property string $provider + * @property array $data + * @property string $label + * @property bool $connected * @property int $project_id */ class NotificationChannel extends AbstractModel { + /** @use HasFactory<\Database\Factories\NotificationChannelFactory> */ use HasFactory; + use Notifiable; protected $fillable = [ @@ -41,7 +43,10 @@ public function provider(): \App\NotificationChannels\NotificationChannel { $class = config('core.notification_channels_providers_class')[$this->provider]; - return new $class($this); + /** @var \App\NotificationChannels\NotificationChannel $provider */ + $provider = new $class($this); + + return $provider; } public static function notifyAll(NotificationInterface $notification): void @@ -52,16 +57,24 @@ public static function notifyAll(NotificationInterface $notification): void } } + /** + * @return BelongsTo + */ public function project(): BelongsTo { return $this->belongsTo(Project::class); } + /** + * @return Builder + */ public static function getByProjectId(int $projectId): Builder { - return self::query() - ->where(function (Builder $query) use ($projectId) { - $query->where('project_id', $projectId)->orWhereNull('project_id'); - }); + /** @var Builder $query */ + $query = NotificationChannel::query(); + + return $query->where(function (Builder $query) use ($projectId): void { + $query->where('project_id', $projectId)->orWhereNull('project_id'); + }); } } diff --git a/app/Models/PersonalAccessToken.php b/app/Models/PersonalAccessToken.php index b6981ad..b007617 100644 --- a/app/Models/PersonalAccessToken.php +++ b/app/Models/PersonalAccessToken.php @@ -12,7 +12,7 @@ * @property int $tokenable_id * @property string $name * @property string $token - * @property array $abilities + * @property array $abilities * @property Carbon $last_used_at * @property Carbon $created_at * @property Carbon $updated_at diff --git a/app/Models/Project.php b/app/Models/Project.php index 0c47708..392db68 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -18,14 +18,16 @@ * @property Carbon $created_at * @property Carbon $updated_at * @property User $user - * @property Collection $servers - * @property Collection $users - * @property Collection $notificationChannels - * @property Collection $sourceControls + * @property Collection $servers + * @property Collection $users + * @property Collection $notificationChannels + * @property Collection $sourceControls */ class Project extends Model { + /** @use HasFactory<\Database\Factories\ProjectFactory> */ use HasFactory; + use HasTimezoneTimestamps; protected $fillable = [ @@ -37,38 +39,57 @@ public static function boot(): void { parent::boot(); - static::deleting(function (Project $project) { - $project->servers()->each(function (Server $server) { + static::deleting(function (Project $project): void { + $project->servers()->each(function ($server): void { + /** @var Server $server */ $server->delete(); }); }); } + /** + * @return BelongsTo + */ public function user(): BelongsTo { return $this->belongsTo(User::class); } + /** + * @return HasMany + */ public function servers(): HasMany { return $this->hasMany(Server::class); } + /** + * @return HasMany + */ public function notificationChannels(): HasMany { return $this->hasMany(NotificationChannel::class); } + /** + * @return BelongsToMany + */ public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'user_project')->withTimestamps(); } + /** + * @return HasMany + */ public function sourceControls(): HasMany { return $this->hasMany(SourceControl::class); } + /** + * @return HasMany + */ public function tags(): HasMany { return $this->hasMany(Tag::class); diff --git a/app/Models/Queue.php b/app/Models/Queue.php index 53b0d3c..4190223 100644 --- a/app/Models/Queue.php +++ b/app/Models/Queue.php @@ -3,6 +3,8 @@ namespace App\Models; use App\Enums\QueueStatus; +use App\SSH\Services\ProcessManager\ProcessManager; +use Database\Factories\QueueFactory; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Facades\Log; @@ -24,6 +26,7 @@ */ class Queue extends AbstractModel { + /** @use HasFactory */ use HasFactory; protected $fillable = [ @@ -48,6 +51,9 @@ class Queue extends AbstractModel 'redirect_stderr' => 'boolean', ]; + /** + * @var array + */ public static array $statusColors = [ QueueStatus::RUNNING => 'success', QueueStatus::CREATING => 'warning', @@ -63,9 +69,14 @@ public static function boot(): void { parent::boot(); - static::deleting(function (Queue $queue) { + static::deleting(function (Queue $queue): void { try { - $queue->server->processManager()->handler()->delete($queue->id, $queue->site_id); + /** @var Service $service */ + $service = $queue->server->processManager(); + /** @var ProcessManager $handler */ + $handler = $service->handler(); + + $handler->delete($queue->id, $queue->site_id); } catch (Throwable $e) { Log::error($e); } @@ -74,7 +85,7 @@ public static function boot(): void public function getServerIdAttribute(int $value): int { - if (! $value) { + if ($value === 0) { $value = $this->site->server_id; $this->fill(['server_id' => $this->site->server_id]); $this->save(); @@ -83,11 +94,17 @@ public function getServerIdAttribute(int $value): int return $value; } + /** + * @return BelongsTo + */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } + /** + * @return BelongsTo + */ public function site(): BelongsTo { return $this->belongsTo(Site::class); diff --git a/app/Models/Script.php b/app/Models/Script.php index e530637..d7c1f8a 100644 --- a/app/Models/Script.php +++ b/app/Models/Script.php @@ -17,14 +17,15 @@ * @property string $content * @property Carbon $created_at * @property Carbon $updated_at - * @property Collection $executions + * @property Collection $executions * @property ?ScriptExecution $lastExecution * @property User $user - * @property int $project_id + * @property ?int $project_id * @property ?Project $project */ class Script extends AbstractModel { + /** @use HasFactory<\Database\Factories\ScriptFactory> */ use HasFactory; protected $fillable = [ @@ -43,46 +44,65 @@ public static function boot(): void { parent::boot(); - static::deleting(function (Script $script) { + static::deleting(function (Script $script): void { $script->executions()->delete(); }); } + /** + * @return BelongsTo + */ public function user(): BelongsTo { return $this->belongsTo(User::class); } + /** + * @return BelongsTo + */ public function project(): BelongsTo { return $this->belongsTo(Project::class); } + /** + * @return array + */ public function getVariables(): array { $variables = []; preg_match_all('/\${(.*?)}/', $this->content, $matches); - foreach ($matches[1] as $match) { - $variables[] = $match; - } + $variables = $matches[1]; return array_unique($variables); } + /** + * @return HasMany + */ public function executions(): HasMany { return $this->hasMany(ScriptExecution::class); } + /** + * @return HasOne + */ public function lastExecution(): HasOne { return $this->hasOne(ScriptExecution::class)->latest(); } + /** + * @return Builder