|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use Illuminate\Console\Command; |
| 6 | +use Illuminate\Support\Env; |
| 7 | +use Illuminate\Support\Facades\Artisan; |
| 8 | +use function Laravel\Prompts\select; |
| 9 | + |
| 10 | +class AuthSwitch extends Command |
| 11 | +{ |
| 12 | + /** |
| 13 | + * The name and signature of the console command. |
| 14 | + * |
| 15 | + * @var string |
| 16 | + */ |
| 17 | + protected $signature = 'auth:switch'; |
| 18 | + |
| 19 | + /** |
| 20 | + * The console command description. |
| 21 | + * |
| 22 | + * @var string |
| 23 | + */ |
| 24 | + protected $description = 'Switch authentication guard'; |
| 25 | + |
| 26 | + /** |
| 27 | + * Execute the console command. |
| 28 | + */ |
| 29 | + public function handle() |
| 30 | + { |
| 31 | + $currentGuard = config('auth.defaults.guard'); |
| 32 | + $guard = select( |
| 33 | + label: 'Select the authentication guard', |
| 34 | + options: [ |
| 35 | + 'api' => 'API - Token based' . ($currentGuard === 'api' ? ' (Current)' : ''), |
| 36 | + 'web' => 'Web - Session based' . ($currentGuard === 'web' ? ' (Current)' : ''), |
| 37 | + ], |
| 38 | + ); |
| 39 | + |
| 40 | + if ($currentGuard === $guard) { |
| 41 | + $this->info('Authentication guard is already ' . $guard . '!'); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + $this->info('Switching authentication guard to ' . $guard . '...'); |
| 46 | + |
| 47 | + Env::writeVariable('AUTH_GUARD', $guard, base_path('.env'), true); |
| 48 | + |
| 49 | + if ($guard === 'web') { |
| 50 | + $this->replaceByPattern(base_path('bootstrap/app.php'), '->statefulApi()', true); |
| 51 | + } else if ($guard === 'api') { |
| 52 | + $this->replaceByPattern(base_path('bootstrap/app.php'), '->statefulApi()', false); |
| 53 | + } |
| 54 | + |
| 55 | + Artisan::call('optimize'); |
| 56 | + |
| 57 | + $this->info('Authentication guard switched to ' . $guard . ' successfully!'); |
| 58 | + } |
| 59 | + |
| 60 | + private function replaceByPattern(string $path, string $pattern, bool $enable): void |
| 61 | + { |
| 62 | + $content = $contentReplaced = file_get_contents($path); |
| 63 | + |
| 64 | + if (!preg_match('@' . preg_quote($pattern) . '@', $content)) { |
| 65 | + $this->fail('Pattern not found in ' . $path); |
| 66 | + } |
| 67 | + |
| 68 | + if ($enable) { |
| 69 | + $contentReplaced = preg_replace('@([/]+[ ]*)?' . preg_quote($pattern) . '@', $pattern, $content); |
| 70 | + } else { |
| 71 | + $contentReplaced = preg_replace('@([/]+[ ]*)?' . preg_quote($pattern) . '@', '//' . $pattern, $content); |
| 72 | + } |
| 73 | + |
| 74 | + if ($contentReplaced !== $content) { |
| 75 | + file_put_contents($path, $contentReplaced); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments