LaravelDocs(中文)

提示 (Prompts)

Laravel Prompts 是一個用於向 CLI 應用程式添加美觀介面的套件

簡介 (Introduction)

Laravel Prompts 是一個 PHP 套件,用於為你的命令列應用程式添加美觀且使用者友善的表單,具有類似瀏覽器的功能,包括預留位置文字和驗證。

Laravel Prompts 非常適合在你的 Artisan 主控台指令 中接受使用者輸入,但它也可以用於任何命令列 PHP 專案。

[!NOTE] Laravel Prompts 支援 macOS、Linux 和 Windows (使用 WSL)。有關更多資訊,請參閱我們關於 不支援的環境與備案 的文件。

安裝 (Installation)

Laravel Prompts 已包含在最新版本的 Laravel 中。

Laravel Prompts 也可以透過 Composer 套件管理器安裝在你的其他 PHP 專案中:

composer require laravel/prompts

可用的提示框 (Available Prompts)

文字輸入 (Text)

text 函式將向使用者提示給定的問題,接受他們的輸入,然後返回它:

use function Laravel\Prompts\text;

$name = text('What is your name?');

你還可以包含預留位置文字、預設值和提示訊息:

$name = text(
    label: 'What is your name?',
    placeholder: 'E.g. Taylor Otwell',
    default: $user?->name,
    hint: 'This will be displayed on your profile.'
);

必填值 (Text Required)

如果你需要輸入值,可以傳遞 required 參數:

$name = text(
    label: 'What is your name?',
    required: true
);

如果你想自訂驗證訊息,也可以傳遞字串:

$name = text(
    label: 'What is your name?',
    required: 'Your name is required.'
);

額外驗證 (Text Validation)

最後,如果你想執行額外的驗證邏輯,可以傳遞閉包給 validate 參數:

$name = text(
    label: 'What is your name?',
    validate: fn (string $value) => match (true) {
        strlen($value) < 3 => 'The name must be at least 3 characters.',
        strlen($value) > 255 => 'The name must not exceed 255 characters.',
        default => null
    }
);

閉包將接收已輸入的值,並可能返回錯誤訊息,如果驗證通過則返回 null

或者,你可以利用 Laravel 的 驗證器 的強大功能。為此,請提供一個包含屬性名稱和所需驗證規則的陣列給 validate 參數:

$name = text(
    label: 'What is your name?',
    validate: ['name' => 'required|max:255|unique:users']
);

多行文字輸入 (Textarea)

textarea 函式將向使用者提示給定的問題,透過多行文字區域接受他們的輸入,然後返回它:

use function Laravel\Prompts\textarea;

$story = textarea('Tell me a story.');

你還可以包含預留位置文字、預設值和提示訊息:

$story = textarea(
    label: 'Tell me a story.',
    placeholder: 'This is a story about...',
    hint: 'This will be displayed on your profile.'
);

必填值 (Textarea Required)

如果你需要輸入值,可以傳遞 required 參數:

$story = textarea(
    label: 'Tell me a story.',
    required: true
);

如果你想自訂驗證訊息,也可以傳遞字串:

$story = textarea(
    label: 'Tell me a story.',
    required: 'A story is required.'
);

額外驗證 (Textarea Validation)

最後,如果你想執行額外的驗證邏輯,可以傳遞閉包給 validate 參數:

$story = textarea(
    label: 'Tell me a story.',
    validate: fn (string $value) => match (true) {
        strlen($value) < 250 => 'The story must be at least 250 characters.',
        strlen($value) > 10000 => 'The story must not exceed 10,000 characters.',
        default => null
    }
);

閉包將接收已輸入的值,並可能返回錯誤訊息,如果驗證通過則返回 null

或者,你可以利用 Laravel 的 驗證器 的強大功能。為此,請提供一個包含屬性名稱和所需驗證規則的陣列給 validate 參數:

$story = textarea(
    label: 'Tell me a story.',
    validate: ['story' => 'required|max:10000']
);

密碼輸入 (Password)

password 函式類似於 text 函式,但使用者的輸入在控制台中輸入時會被遮蔽。這在詢問密碼等敏感資訊時很有用:

use function Laravel\Prompts\password;

$password = password('What is your password?');

你還可以包含預留位置文字和提示訊息:

$password = password(
    label: 'What is your password?',
    placeholder: 'password',
    hint: 'Minimum 8 characters.'
);

必填值 (Password Required)

如果你需要輸入值,可以傳遞 required 參數:

$password = password(
    label: 'What is your password?',
    required: true
);

如果你想自訂驗證訊息,也可以傳遞字串:

$password = password(
    label: 'What is your password?',
    required: 'The password is required.'
);

額外驗證 (Password Validation)

最後,如果你想執行額外的驗證邏輯,可以傳遞閉包給 validate 參數:

$password = password(
    label: 'What is your password?',
    validate: fn (string $value) => match (true) {
        strlen($value) < 8 => 'The password must be at least 8 characters.',
        default => null
    }
);

閉包將接收已輸入的值,並可能返回錯誤訊息,如果驗證通過則返回 null

或者,你可以利用 Laravel 的 驗證器 的強大功能。為此,請提供一個包含屬性名稱和所需驗證規則的陣列給 validate 參數:

$password = password(
    label: 'What is your password?',
    validate: ['password' => 'min:8']
);

確認 (Confirm)

如果你需要詢問使用者「是或否」的確認,可以使用 confirm 函式。使用者可以使用方向鍵或按 yn 來選擇他們的回應。此函式將返回 truefalse

use function Laravel\Prompts\confirm;

$confirmed = confirm('Do you accept the terms?');

你還可以包含預設值、自訂「是」和「否」標籤的措辭,以及提示訊息:

$confirmed = confirm(
    label: 'Do you accept the terms?',
    default: false,
    yes: 'I accept',
    no: 'I decline',
    hint: 'The terms must be accepted to continue.'
);

要求「是」 (Confirm Required)

如果有必要,你可以透過傳遞 required 參數來要求使用者選擇「是」:

$confirmed = confirm(
    label: 'Do you accept the terms?',
    required: true
);

如果你想自訂驗證訊息,也可以傳遞字串:

$confirmed = confirm(
    label: 'Do you accept the terms?',
    required: 'You must accept the terms to continue.'
);

選擇 (Select)

如果你需要使用者從一組預定義的選項中進行選擇,可以使用 select 函式:

use function Laravel\Prompts\select;

$role = select(
    label: 'What role should the user have?',
    options: ['Member', 'Contributor', 'Owner']
);

你還可以指定預設選項和提示訊息:

$role = select(
    label: 'What role should the user have?',
    options: ['Member', 'Contributor', 'Owner'],
    default: 'Owner',
    hint: 'The role may be changed at any time.'
);

你也可以傳遞關聯陣列給 options 參數,以返回選定的鍵而不是其值:

$role = select(
    label: 'What role should the user have?',
    options: [
        'member' => 'Member',
        'contributor' => 'Contributor',
        'owner' => 'Owner',
    ],
    default: 'owner'
);

在列表開始捲動之前,最多會顯示五個選項。你可以透過傳遞 scroll 參數來自訂此設定:

$role = select(
    label: 'Which category would you like to assign?',
    options: Category::pluck('name', 'id'),
    scroll: 10
);

額外驗證 (Select Validation)

與其他提示函式不同,select 函式不接受 required 參數,因為不可能不選擇任何內容。但是,如果你需要呈現一個選項但阻止它被選中,你可以傳遞閉包給 validate 參數:

$role = select(
    label: 'What role should the user have?',
    options: [
        'member' => 'Member',
        'contributor' => 'Contributor',
        'owner' => 'Owner',
    ],
    validate: fn (string $value) =>
        $value === 'owner' && User::where('role', 'owner')->exists()
            ? 'An owner already exists.'
            : null
);

如果 options 參數是關聯陣列,那麼閉包將接收選定的鍵,否則它將接收選定的值。閉包可能會返回錯誤訊息,如果驗證通過則返回 null

多重選擇 (Multi-select)

如果你需要使用者能夠選擇多個選項,可以使用 multiselect 函式:

use function Laravel\Prompts\multiselect;

$permissions = multiselect(
    label: 'What permissions should be assigned?',
    options: ['Read', 'Create', 'Update', 'Delete']
);

你還可以指定預設選項和提示訊息:

use function Laravel\Prompts\multiselect;

$permissions = multiselect(
    label: 'What permissions should be assigned?',
    options: ['Read', 'Create', 'Update', 'Delete'],
    default: ['Read', 'Create'],
    hint: 'Permissions may be updated at any time.'
);

你也可以傳遞關聯陣列給 options 參數,以返回選定選項的鍵而不是其值:

$permissions = multiselect(
    label: 'What permissions should be assigned?',
    options: [
        'read' => 'Read',
        'create' => 'Create',
        'update' => 'Update',
        'delete' => 'Delete',
    ],
    default: ['read', 'create']
);

在列表開始捲動之前,最多會顯示五個選項。你可以透過傳遞 scroll 參數來自訂此設定:

$categories = multiselect(
    label: 'What categories should be assigned?',
    options: Category::pluck('name', 'id'),
    scroll: 10
);

必填值 (Multiselect Required)

預設情況下,使用者可以選擇零個或多個選項。你可以傳遞 required 參數來強制選擇一個或多個選項:

$categories = multiselect(
    label: 'What categories should be assigned?',
    options: Category::pluck('name', 'id'),
    required: true
);

如果你想自訂驗證訊息,可以提供字串給 required 參數:

$categories = multiselect(
    label: 'What categories should be assigned?',
    options: Category::pluck('name', 'id'),
    required: 'You must select at least one category'
);

額外驗證 (Multiselect Validation)

如果你需要呈現一個選項但阻止它被選中,你可以傳遞閉包給 validate 參數:

$permissions = multiselect(
    label: 'What permissions should the user have?',
    options: [
        'read' => 'Read',
        'create' => 'Create',
        'update' => 'Update',
        'delete' => 'Delete',
    ],
    validate: fn (array $values) => ! in_array('read', $values)
        ? 'All users require the read permission.'
        : null
);

如果 options 參數是關聯陣列,那麼閉包將接收選定的鍵,否則它將接收選定的值。閉包可能會返回錯誤訊息,如果驗證通過則返回 null

建議 (Suggest)

suggest 函式可用於為可能的選擇提供自動完成功能。無論自動完成提示如何,使用者仍然可以提供任何答案:

use function Laravel\Prompts\suggest;

$name = suggest('What is your name?', ['Taylor', 'Dayle']);

或者,你可以傳遞閉包作為 suggest 函式的第二個參數。每次使用者輸入字元時都會呼叫該閉包。閉包應接受包含使用者目前輸入的字串參數,並返回用於自動完成的選項陣列:

$name = suggest(
    label: 'What is your name?',
    options: fn ($value) => collect(['Taylor', 'Dayle'])
        ->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true))
)

你還可以包含預留位置文字、預設值和提示訊息:

$name = suggest(
    label: 'What is your name?',
    options: ['Taylor', 'Dayle'],
    placeholder: 'E.g. Taylor',
    default: $user?->name,
    hint: 'This will be displayed on your profile.'
);

必填值 (Suggest Required)

如果你需要輸入值,可以傳遞 required 參數:

$name = suggest(
    label: 'What is your name?',
    options: ['Taylor', 'Dayle'],
    required: true
);

如果你想自訂驗證訊息,也可以傳遞字串:

$name = suggest(
    label: 'What is your name?',
    options: ['Taylor', 'Dayle'],
    required: 'Your name is required.'
);

額外驗證 (Suggest Validation)

最後,如果你想執行額外的驗證邏輯,可以傳遞閉包給 validate 參數:

$name = suggest(
    label: 'What is your name?',
    options: ['Taylor', 'Dayle'],
    validate: fn (string $value) => match (true) {
        strlen($value) < 3 => 'The name must be at least 3 characters.',
        strlen($value) > 255 => 'The name must not exceed 255 characters.',
        default => null
    }
);

閉包將接收已輸入的值,並可能返回錯誤訊息,如果驗證通過則返回 null

或者,你可以利用 Laravel 的 驗證器 的強大功能。為此,請提供一個包含屬性名稱和所需驗證規則的陣列給 validate 參數:

$name = suggest(
    label: 'What is your name?',
    options: ['Taylor', 'Dayle'],
    validate: ['name' => 'required|min:3|max:255']
);

如果你有許多選項供使用者選擇,search 函式允許使用者輸入搜尋查詢來過濾結果,然後使用方向鍵選擇選項:

use function Laravel\Prompts\search;

$id = search(
    label: 'Search for the user that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : []
);

閉包將接收使用者目前輸入的文字,並且必須返回選項陣列。如果你返回關聯陣列,則將返回選定選項的鍵,否則將返回其值。

當過濾你打算返回值的陣列時,你應該使用 array_values 函式或 values 集合方法,以確保陣列不會變成關聯陣列:

$names = collect(['Taylor', 'Abigail']);

$selected = search(
    label: 'Search for the user that should receive the mail',
    options: fn (string $value) => $names
        ->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true))
        ->values()
        ->all(),
);

你還可以包含預留位置文字和提示訊息:

$id = search(
    label: 'Search for the user that should receive the mail',
    placeholder: 'E.g. Taylor Otwell',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    hint: 'The user will receive an email immediately.'
);

在列表開始捲動之前,最多會顯示五個選項。你可以透過傳遞 scroll 參數來自訂此設定:

$id = search(
    label: 'Search for the user that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    scroll: 10
);

額外驗證 (Search Validation)

如果你想執行額外的驗證邏輯,可以傳遞閉包給 validate 參數:

$id = search(
    label: 'Search for the user that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    validate: function (int|string $value) {
        $user = User::findOrFail($value);

        if ($user->opted_out) {
            return 'This user has opted-out of receiving mail.';
        }
    }
);

如果 options 閉包返回關聯陣列,那麼閉包將接收選定的鍵,否則它將接收選定的值。閉包可能會返回錯誤訊息,如果驗證通過則返回 null

如果你有許多可搜尋的選項,並且需要使用者能夠選擇多個項目,multisearch 函式允許使用者輸入搜尋查詢來過濾結果,然後使用方向鍵和空白鍵選擇選項:

use function Laravel\Prompts\multisearch;

$ids = multisearch(
    'Search for the users that should receive the mail',
    fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : []
);

閉包將接收使用者目前輸入的文字,並且必須返回選項陣列。如果你返回關聯陣列,則將返回選定選項的鍵;否則,將返回其值。

當過濾你打算返回值的陣列時,你應該使用 array_values 函式或 values 集合方法,以確保陣列不會變成關聯陣列:

$names = collect(['Taylor', 'Abigail']);

$selected = multisearch(
    label: 'Search for the users that should receive the mail',
    options: fn (string $value) => $names
        ->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true))
        ->values()
        ->all(),
);

你還可以包含預留位置文字和提示訊息:

$ids = multisearch(
    label: 'Search for the users that should receive the mail',
    placeholder: 'E.g. Taylor Otwell',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    hint: 'The user will receive an email immediately.'
);

在列表開始捲動之前,最多會顯示五個選項。你可以透過傳遞 scroll 參數來自訂此設定:

$ids = multisearch(
    label: 'Search for the users that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    scroll: 10
);

必填值 (Multisearch Required)

預設情況下,使用者可以選擇零個或多個選項。你可以傳遞 required 參數來強制選擇一個或多個選項:

$ids = multisearch(
    label: 'Search for the users that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    required: true
);

如果你想自訂驗證訊息,可以提供字串給 required 參數:

$ids = multisearch(
    label: 'Search for the users that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    required: 'You must select at least one user.'
);

額外驗證 (Multisearch Validation)

如果你想執行額外的驗證邏輯,可以傳遞閉包給 validate 參數:

$ids = multisearch(
    label: 'Search for the users that should receive the mail',
    options: fn (string $value) => strlen($value) > 0
        ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
        : [],
    validate: function (array $values) {
        $optedOut = User::whereLike('name', '%a%')->findMany($values);

        if ($optedOut->isNotEmpty()) {
            return $optedOut->pluck('name')->join(', ', ', and ').' have opted out.';
        }
    }
);

如果 options 閉包返回關聯陣列,那麼閉包將接收選定的鍵;否則,它將接收選定的值。閉包可能會返回錯誤訊息,如果驗證通過則返回 null

暫停 (Pause)

pause 函式可用於向使用者顯示資訊文字,並等待他們按 Enter / Return 鍵確認是否繼續:

use function Laravel\Prompts\pause;

pause('Press ENTER to continue.');

驗證前轉換輸入 (Transforming Input Before Validation)

有時你可能希望在驗證發生之前轉換提示輸入。例如,你可能希望從任何提供的字串中刪除空白。為了實現這一點,許多提示函式提供了 transform 參數,該參數接受一個閉包:

$name = text(
    label: 'What is your name?',
    transform: fn (string $value) => trim($value),
    validate: fn (string $value) => match (true) {
        strlen($value) < 3 => 'The name must be at least 3 characters.',
        strlen($value) > 255 => 'The name must not exceed 255 characters.',
        default => null
    }
);

表單 (Forms)

通常,你會有許多提示框需要按順序顯示以收集資訊,然後再執行其他操作。你可以使用 form 函式來建立一組分組的提示框供使用者完成:

use function Laravel\Prompts\form;

$responses = form()
    ->text('What is your name?', required: true)
    ->password('What is your password?', validate: ['password' => 'min:8'])
    ->confirm('Do you accept the terms?')
    ->submit();

submit 方法將返回一個數字索引陣列,其中包含來自表單提示框的所有回應。但是,你可以透過 name 參數為每個提示框提供名稱。提供名稱後,可以透過該名稱存取命名提示框的回應:

use App\Models\User;
use function Laravel\Prompts\form;

$responses = form()
    ->text('What is your name?', required: true, name: 'name')
    ->password(
        label: 'What is your password?',
        validate: ['password' => 'min:8'],
        name: 'password'
    )
    ->confirm('Do you accept the terms?')
    ->submit();

User::create([
    'name' => $responses['name'],
    'password' => $responses['password'],
]);

使用 form 函式的主要好處是使用者可以使用 CTRL + U 返回表單中的上一個提示框。這允許使用者修正錯誤或更改選擇,而無需取消並重新啟動整個表單。

如果你需要對表單中的提示框進行更精細的控制,可以呼叫 add 方法,而不是直接呼叫其中一個提示框函式。add 方法會傳遞使用者提供的所有先前回應:

use function Laravel\Prompts\form;
use function Laravel\Prompts\outro;
use function Laravel\Prompts\text;

$responses = form()
    ->text('What is your name?', required: true, name: 'name')
    ->add(function ($responses) {
        return text("How old are you, {$responses['name']}?");
    }, name: 'age')
    ->submit();

outro("Your name is {$responses['name']} and you are {$responses['age']} years old.");

訊息提示 (Informational Messages)

noteinfowarningerroralert 函式可用於顯示訊息提示:

use function Laravel\Prompts\info;

info('Package installed successfully.');

表格 (Tables)

table 函式使顯示多行和多列資料變得容易。你只需要提供欄位名稱和表格資料:

use function Laravel\Prompts\table;

table(
    headers: ['Name', 'Email'],
    rows: User::all(['name', 'email'])->toArray()
);

旋轉指示器 (Spin)

spin 函式在執行指定的回呼時顯示一個旋轉指示器以及可選的訊息。它用於指示正在進行的處理,並在完成後返回回呼的結果:

use function Laravel\Prompts\spin;

$response = spin(
    callback: fn () => Http::get('http://example.com'),
    message: 'Fetching response...'
);

[!WARNING] > spin 函式需要 PCNTL PHP 擴充功能才能為旋轉指示器設定動畫。當此擴充功能不可用時,將顯示靜態版本的旋轉指示器。

進度條 (Progress Bars)

對於長時間執行的任務,顯示進度條以通知使用者任務完成的程度會很有幫助。使用 progress 函式,Laravel 將顯示一個進度條,並針對給定可迭代值的每次迭代推進其進度:

use function Laravel\Prompts\progress;

$users = progress(
    label: 'Updating users',
    steps: User::all(),
    callback: fn ($user) => $this->performTask($user)
);

progress 函式的作用類似於 map 函式,並將返回一個包含每次迭代回呼返回值的陣列。

回呼還可以接受 Laravel\Prompts\Progress 實例,允許你在每次迭代時修改標籤和提示:

$users = progress(
    label: 'Updating users',
    steps: User::all(),
    callback: function ($user, $progress) {
        $progress
            ->label("Updating {$user->name}")
            ->hint("Created on {$user->created_at}");

        return $this->performTask($user);
    },
    hint: 'This may take some time.'
);

有時,你可能需要更手動地控制進度條的推進方式。首先,定義該過程將迭代的總步驟數。然後,在處理每個項目後透過 advance 方法推進進度條:

$progress = progress(label: 'Updating users', steps: 10);

$users = User::all();

$progress->start();

foreach ($users as $user) {
    $this->performTask($user);

    $progress->advance();
}

$progress->finish();

清除終端機 (Clearing the Terminal)

clear 函式可用於清除使用者的終端機:

use function Laravel\Prompts\clear;

clear();

終端機注意事項 (Terminal Considerations)

終端機寬度 (Terminal Width)

如果任何標籤、選項或驗證訊息的長度超過使用者終端機中的「列」數,它將自動截斷以適應。如果你的使用者可能使用較窄的終端機,請考慮最小化這些字串的長度。通常安全的長度上限為 74 個字元,以支援 80 個字元的終端機。

終端機高度 (Terminal Height)

對於任何接受 scroll 參數的提示框,設定的值將自動減少以適應使用者終端機的高度,包括驗證訊息的空間。

不支援的環境與備案 (Unsupported Environments and Fallbacks)

Laravel Prompts 支援 macOS、Linux 和 Windows (使用 WSL)。由於 Windows 版本 PHP 的限制,目前無法在 WSL 之外的 Windows 上使用 Laravel Prompts。

因此,Laravel Prompts 支援退回到替代實作,例如 Symfony Console Question Helper

[!NOTE] 當在 Laravel 框架中使用 Laravel Prompts 時,每個提示框的備案已為你設定好,並將在不支援的環境中自動啟用。

備案條件 (Fallback Conditions)

如果你沒有使用 Laravel,或者需要自訂何時使用備案行為,你可以傳遞布林值給 Prompt 類別上的 fallbackWhen 靜態方法:

use Laravel\Prompts\Prompt;

Prompt::fallbackWhen(
    ! $input->isInteractive() || windows_os() || app()->runningUnitTests()
);

備案行為 (Fallback Behavior)

如果你沒有使用 Laravel,或者需要自訂備案行為,你可以傳遞閉包給每個提示框類別上的 fallbackUsing 靜態方法:

use Laravel\Prompts\TextPrompt;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;

TextPrompt::fallbackUsing(function (TextPrompt $prompt) use ($input, $output) {
    $question = (new Question($prompt->label, $prompt->default ?: null))
        ->setValidator(function ($answer) use ($prompt) {
            if ($prompt->required && $answer === null) {
                throw new \RuntimeException(
                    is_string($prompt->required) ? $prompt->required : 'Required.'
                );
            }

            if ($prompt->validate) {
                $error = ($prompt->validate)($answer ?? '');

                if ($error) {
                    throw new \RuntimeException($error);
                }
            }

            return $answer;
        });

    return (new SymfonyStyle($input, $output))
        ->askQuestion($question);
});

必須為每個提示框類別單獨設定備案。閉包將接收提示框類別的實例,並且必須返回適當的提示框類型。

測試 (Testing)

Laravel 提供了多種方法來測試你的指令是否顯示預期的 Prompt 訊息:

test('report generation', function () {
    $this->artisan('report:generate')
        ->expectsPromptsInfo('Welcome to the application!')
        ->expectsPromptsWarning('This action cannot be undone')
        ->expectsPromptsError('Something went wrong')
        ->expectsPromptsAlert('Important notice!')
        ->expectsPromptsIntro('Starting process...')
        ->expectsPromptsOutro('Process completed!')
        ->expectsPromptsTable(
            headers: ['Name', 'Email'],
            rows: [
                ['Taylor Otwell', 'taylor@example.com'],
                ['Jason Beggs', 'jason@example.com'],
            ]
        )
        ->assertExitCode(0);
});
public function test_report_generation(): void
{
    $this->artisan('report:generate')
        ->expectsPromptsInfo('Welcome to the application!')
        ->expectsPromptsWarning('This action cannot be undone')
        ->expectsPromptsError('Something went wrong')
        ->expectsPromptsAlert('Important notice!')
        ->expectsPromptsIntro('Starting process...')
        ->expectsPromptsOutro('Process completed!')
        ->expectsPromptsTable(
            headers: ['Name', 'Email'],
            rows: [
                ['Taylor Otwell', 'taylor@example.com'],
                ['Jason Beggs', 'jason@example.com'],
            ]
        )
        ->assertExitCode(0);
}