|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Services\System; |
| 4 | + |
| 5 | +use App\Models\SystemUpdate; |
| 6 | +use Illuminate\Support\Facades\Log; |
| 7 | +use Symfony\Component\Process\Process; |
| 8 | + |
| 9 | +class SystemUpdateService |
| 10 | +{ |
| 11 | + public function runUpdate(): SystemUpdate |
| 12 | + { |
| 13 | + $output = ''; |
| 14 | + $status = 'successful'; |
| 15 | + |
| 16 | + $version = trim(shell_exec('git rev-parse HEAD')); |
| 17 | + $commitTitle = trim(shell_exec('git log -1 --pretty=%s')); |
| 18 | + $commitDescription = trim(shell_exec('git log -1 --pretty=%b')); |
| 19 | + |
| 20 | + $update = SystemUpdate::create([ |
| 21 | + 'version' => $version, |
| 22 | + 'commit_title' => $commitTitle, |
| 23 | + 'commit_description' => $commitDescription, |
| 24 | + 'update_log' => '', |
| 25 | + 'status' => 'running', |
| 26 | + ]); |
| 27 | + |
| 28 | + $commands = [ |
| 29 | + 'git fetch origin', |
| 30 | + 'git reset --hard origin/main', |
| 31 | + 'git clean -fd', |
| 32 | + 'php artisan migrate', |
| 33 | + 'php artisan optimize:clear', |
| 34 | + 'php artisan queue:restart', |
| 35 | + 'npm install', |
| 36 | + 'npm run build', |
| 37 | + ]; |
| 38 | + |
| 39 | + foreach ($commands as $command) { |
| 40 | + $output .= "Running: $command\n"; |
| 41 | + try { |
| 42 | + $process = Process::fromShellCommandline($command, base_path(), null, null, 300); |
| 43 | + $process->run(); |
| 44 | + |
| 45 | + $output .= $process->getOutput() . "\n"; |
| 46 | + if (!$process->isSuccessful()) { |
| 47 | + $output .= "Error: " . $process->getErrorOutput() . "\n"; |
| 48 | + $status = 'failed'; |
| 49 | + break; |
| 50 | + } |
| 51 | + } catch (\Throwable $e) { |
| 52 | + $output .= "Exception: " . $e->getMessage() . "\n"; |
| 53 | + $status = 'failed'; |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + $update->update([ |
| 59 | + 'update_log' => $output, |
| 60 | + 'status' => $status, |
| 61 | + ]); |
| 62 | + |
| 63 | + return $update; |
| 64 | + } |
| 65 | + |
| 66 | + public function checkForUpdates(): ?array |
| 67 | + { |
| 68 | + $currentVersion = trim(shell_exec('git rev-parse HEAD')); |
| 69 | + $latestVersion = trim(shell_exec('git ls-remote origin -h refs/heads/main | cut -f1')); |
| 70 | + |
| 71 | + if ($currentVersion !== $latestVersion) { |
| 72 | + return [ |
| 73 | + 'version' => $latestVersion, |
| 74 | + 'title' => trim(shell_exec("git log $latestVersion -1 --pretty=%s")), |
| 75 | + 'description' => trim(shell_exec("git log $latestVersion -1 --pretty=%b")), |
| 76 | + ]; |
| 77 | + } |
| 78 | + |
| 79 | + return null; |
| 80 | + } |
| 81 | +} |
0 commit comments