2024/01/24

Lumen 撰寫類似Laravel 產生序號Command

Console/Kernel配置:
<?php

namespace App\Console;

use App\Console\Commands\GenerateKeyCommand;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        GenerateKeyCommand::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //
    }
}

代碼:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateKeyCommand extends Command
{
    // 命令名稱
    protected $signature = 'key:generate';

    // 命令描述
    protected $description = 'Generate a new application key';

    // 命令執行
    public function handle()
    {
        //取得環境檔案路徑
        $envPath = $this->getEnvPath();

        if (file_exists($envPath)) { //檔案存在才詢問
            //取得env檔案內容
            $envContent = file_get_contents($envPath);

            if (preg_match('/^APP_KEY=\S+/m', $envContent)) { // 判斷是否已經有APP_KEY
                if ($this->confirm('APP_KEY already exists. Do you wish to replace it?')) {
                    //產生Base64的亂數字串
                    $key = base64_encode(openssl_random_pseudo_bytes(32));
                    $envContent = preg_replace('/^APP_KEY=.*/m', "APP_KEY=$key", $envContent);
                    file_put_contents($envPath, $envContent);
                    $this->info("Application key [$key] set successfully.");
                } else {
                    $this->info('Operation cancelled.');
                }
            } else { // 沒有APP_KEY就直接產生
                //產生Base64的亂數字串
                $key = base64_encode(openssl_random_pseudo_bytes(32));
                $envContent = preg_replace('/^APP_KEY=.*/m', "APP_KEY=$key", $envContent);
                file_put_contents($envPath, $envContent);
                $this->info("Application key [$key] set successfully.");
            }
        } else { //檔案不存在的話就說失敗
            $this->error('Application key not set. Please check your .env file.');
        }
    }

    /**
     * 取得環境檔案路徑
     * @return string
     */
    private function getEnvPath(): string
    {
        return base_path('.env');
    }
}