0 追蹤者

類別 yii\helpers\Console

繼承關係yii\helpers\Console » yii\helpers\BaseConsole
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/helpers/Console.php

Console 助手類別為命令列相關任務提供實用的方法,例如取得輸入或格式化和著色輸出。

公有方法

隱藏繼承的方法

方法 描述 定義於
ansiColorizedSubstr() 傳回由 start 和 length 參數指定的字串部分,包含 ANSI 顏色代碼。 yii\helpers\BaseConsole
ansiFormat() 將傳回以給定的 ANSI 樣式格式化的字串。 yii\helpers\BaseConsole
ansiFormatCode() 傳回 ANSI 格式代碼。 yii\helpers\BaseConsole
ansiStrlen() 傳回不含 ANSI 顏色代碼的字串長度。 yii\helpers\BaseConsole
ansiStrwidth() 傳回不含 ANSI 顏色代碼的字串寬度。 yii\helpers\BaseConsole
ansiToHtml() 將 ANSI 格式化的字串轉換為 HTML。 yii\helpers\BaseConsole
beginAnsiFormat() 輸出 ANSI 格式代碼,該代碼會影響之後列印的任何文字的格式。 yii\helpers\BaseConsole
clearLine() 清除游標目前所在的行,方法是傳送 ANSI 控制代碼 EL 並帶參數 2 給終端機。 yii\helpers\BaseConsole
clearLineAfterCursor() 透過傳送 ANSI 控制碼 EL 及參數 0 到終端機,清除從游標位置到行尾的文字。 yii\helpers\BaseConsole
clearLineBeforeCursor() 透過傳送 ANSI 控制碼 EL 及參數 1 到終端機,清除從游標位置到行首的文字。 yii\helpers\BaseConsole
clearScreen() 透過傳送 ANSI 控制碼 ED 及參數 2 到終端機,清除整個螢幕內容。 yii\helpers\BaseConsole
clearScreenAfterCursor() 透過傳送 ANSI 控制碼 ED 及參數 0 到終端機,清除從游標位置到螢幕底端的文字。 yii\helpers\BaseConsole
clearScreenBeforeCursor() 透過傳送 ANSI 控制碼 ED 及參數 1 到終端機,清除從游標位置到螢幕頂端的文字。 yii\helpers\BaseConsole
confirm() 要求使用者輸入 y 或 n 以確認。 yii\helpers\BaseConsole
endAnsiFormat() 重設先前方法 beginAnsiFormat() 設定的任何 ANSI 格式。此後的任何輸出都將具有預設文字格式。 yii\helpers\BaseConsole
endProgress() 結束由 startProgress() 啟動的進度列。 yii\helpers\BaseConsole
error() 將文字列印到 STDERR,並附加歸位字元 (PHP_EOL)。 yii\helpers\BaseConsole
errorSummary() 產生驗證錯誤的摘要。 yii\helpers\BaseConsole
escape() 跳脫 % 字元,使其在字串被 renderColoredString() 解析時不會被解釋為顏色代碼。 yii\helpers\BaseConsole
getScreenSize() 傳回終端機螢幕尺寸。 yii\helpers\BaseConsole
hideCursor() 透過傳送 ANSI DECTCEM 代碼 ?25l 給終端機來隱藏游標。 yii\helpers\BaseConsole
input() 要求使用者輸入。當使用者輸入歸位字元 (PHP_EOL) 時結束。可選地,它也提供提示字元。 yii\helpers\BaseConsole
isRunningOnWindows() 如果主控台在 Windows 上執行,則傳回 true。 yii\helpers\BaseConsole
markdownToAnsi() 透過套用一些 ANSI 格式,將 Markdown 轉換為在主控台環境中更易於閱讀的形式。 yii\helpers\BaseConsole
moveCursorBackward() 透過傳送 ANSI 控制代碼 CUB 給終端機,將終端機游標向後移動。 yii\helpers\BaseConsole
moveCursorDown() 透過傳送 ANSI 控制代碼 CUD 給終端機,將終端機游標向下移動。 yii\helpers\BaseConsole
moveCursorForward() 透過傳送 ANSI 控制代碼 CUF 給終端機,將終端機游標向前移動。 yii\helpers\BaseConsole
moveCursorNextLine() 透過傳送 ANSI 控制代碼 CNL 給終端機,將終端機游標移動到下一行的開頭。 yii\helpers\BaseConsole
moveCursorPrevLine() 透過傳送 ANSI 控制代碼 CPL 給終端機,將終端機游標移動到上一行的開頭。 yii\helpers\BaseConsole
moveCursorTo() 透過傳送 ANSI 控制代碼 CUP 或 CHA 給終端機,將游標移動到以欄和列給定的絕對位置。 yii\helpers\BaseConsole
moveCursorUp() 透過傳送 ANSI 控制代碼 CUU 給終端機,將終端機游標向上移動。 yii\helpers\BaseConsole
output() 將文字列印到 STDOUT,並附加歸位字元 (PHP_EOL)。 yii\helpers\BaseConsole
prompt() 提示使用者輸入並驗證輸入。 yii\helpers\BaseConsole
renderColoredString() 透過將像 %y (代表黃色) 這樣的模式替換為 ANSI 控制代碼,將字串轉換為 ANSI 格式。 yii\helpers\BaseConsole
restoreCursorPosition() 透過傳送 ANSI 控制代碼 RCP 給終端機,還原使用 saveCursorPosition() 儲存的游標位置。 yii\helpers\BaseConsole
saveCursorPosition() 透過傳送 ANSI 控制代碼 SCP 給終端機,儲存目前的游標位置。 yii\helpers\BaseConsole
scrollDown() 透過傳送 ANSI 控制代碼 SD 給終端機,將整個頁面向下捲動。 yii\helpers\BaseConsole
scrollUp() 透過傳送 ANSI 控制代碼 SU 給終端機,將整個頁面向上捲動。 yii\helpers\BaseConsole
select() 提供使用者從選項中選擇。輸入 '?' 將顯示選項列表及其說明。 yii\helpers\BaseConsole
showCursor() 當游標被 hideCursor() 隱藏時,透過傳送 ANSI DECTCEM 代碼 ?25h 給終端機,再次顯示游標。 yii\helpers\BaseConsole
startProgress() 開始在螢幕上顯示進度列。 yii\helpers\BaseConsole
stderr() 將字串列印到 STDERR。 yii\helpers\BaseConsole
stdin() 從 STDIN 取得輸入,並傳回已修剪尾端 EOL 字元的字串。 yii\helpers\BaseConsole
stdout() 將字串列印到 STDOUT。 yii\helpers\BaseConsole
streamSupportsAnsiColors() 如果資料流支援色彩化,則傳回 true。如果資料流不支援 ANSI 顏色,則會停用 ANSI 顏色。 yii\helpers\BaseConsole
stripAnsiFormat() 從字串中移除 ANSI 控制代碼。 yii\helpers\BaseConsole
updateProgress() 更新由 startProgress() 啟動的進度列。 yii\helpers\BaseConsole
wrapText() 自動換行文字,並加上縮排以符合螢幕尺寸。 yii\helpers\BaseConsole
xtermBgColor() 傳回 xterm 背景顏色的 ANSI 格式代碼。 yii\helpers\BaseConsole
xtermFgColor() 傳回 xterm 前景顏色的 ANSI 格式代碼。 yii\helpers\BaseConsole

方法詳情

隱藏繼承的方法

ansiColorizedSubstr() public static method

定義於: yii\helpers\BaseConsole::ansiColorizedSubstr()

傳回由 start 和 length 參數指定的字串部分,包含 ANSI 顏色代碼。

如果字串有顏色代碼,則會傳回 "TEXT_COLOR + TEXT_STRING + DEFAULT_COLOR",否則只會傳回 "TEXT_STRING"。

public static string ansiColorizedSubstr ( $string, $start, $length )
$string string
$start integer
$length integer

                public static function ansiColorizedSubstr($string, $start, $length)
{
    if ($start < 0 || $length <= 0) {
        return '';
    }
    $textItems = preg_split(self::ansiCodesPattern(), (string)$string);
    preg_match_all(self::ansiCodesPattern(), (string)$string, $colors);
    $colors = count($colors) ? $colors[0] : [];
    array_unshift($colors, '');
    $result = '';
    $curPos = 0;
    $inRange = false;
    foreach ($textItems as $k => $textItem) {
        $color = $colors[$k];
        if ($curPos <= $start && $start < $curPos + Console::ansiStrwidth($textItem)) {
            $text = mb_substr($textItem, $start - $curPos, null, Yii::$app->charset);
            $inRange = true;
        } else {
            $text = $textItem;
        }
        if ($inRange) {
            $result .= $color . $text;
            $diff = $length - Console::ansiStrwidth($result);
            if ($diff <= 0) {
                if ($diff < 0) {
                    $result = mb_substr($result, 0, $diff, Yii::$app->charset);
                }
                $defaultColor = static::renderColoredString('%n');
                if ($color && $color != $defaultColor) {
                    $result .= $defaultColor;
                }
                break;
            }
        }
        $curPos += mb_strlen($textItem, Yii::$app->charset);
    }
    return $result;
}

            
ansiFormat() public static method

定義於: yii\helpers\BaseConsole::ansiFormat()

將傳回以給定的 ANSI 樣式格式化的字串。

public static string ansiFormat ( $string, $format = [] )
$string string

要格式化的字串

$format array

包含格式化值的陣列。您可以傳遞任何 FG_*BG_*TEXT_* 常數,以及 xtermFgColor()xtermBgColor() 來指定格式。

                public static function ansiFormat($string, $format = [])
{
    $code = implode(';', $format);
    return "\033[0m" . ($code !== '' ? "\033[" . $code . 'm' : '') . $string . "\033[0m";
}

            
ansiFormatCode() public static method

定義於: yii\helpers\BaseConsole::ansiFormatCode()

傳回 ANSI 格式代碼。

public static string ansiFormatCode ( $format )
$format array

包含格式化值的陣列。您可以傳遞任何 FG_*BG_*TEXT_* 常數,以及 xtermFgColor()xtermBgColor() 來指定格式。

return string

根據給定的格式化常數的 ANSI 格式代碼。

                public static function ansiFormatCode($format)
{
    return "\033[" . implode(';', $format) . 'm';
}

            
ansiStrlen() public static method

定義於: yii\helpers\BaseConsole::ansiStrlen()

傳回不含 ANSI 顏色代碼的字串長度。

public static integer ansiStrlen ( $string )
$string string

要測量的字串

return integer

字串的長度,不包含 ANSI 格式字元

                public static function ansiStrlen($string)
{
    return mb_strlen(static::stripAnsiFormat($string));
}

            
ansiStrwidth() public static method (available since version 2.0.36)

定義於: yii\helpers\BaseConsole::ansiStrwidth()

傳回不含 ANSI 顏色代碼的字串寬度。

public static integer ansiStrwidth ( $string )
$string string

要測量的字串

return integer

字串的寬度,不包含 ANSI 格式字元

                public static function ansiStrwidth($string)
{
    return mb_strwidth(static::stripAnsiFormat($string), Yii::$app->charset);
}

            
ansiToHtml() public static method

定義於: yii\helpers\BaseConsole::ansiToHtml()

將 ANSI 格式化的字串轉換為 HTML。

注意:目前不支援 xTerm 256 位元色彩。

public static string ansiToHtml ( $string, $styleMap = [] )
$string string

要轉換的字串。

$styleMap array

ANSI 控制代碼 (例如 FG_COLORBOLD) 到一組 CSS 樣式定義的可選映射。CSS 樣式定義表示為一個陣列,其中陣列鍵對應於 CSS 樣式屬性名稱,而值是 CSS 值。值可以是陣列,這些陣列將在呈現時合併並使用 ' ' 結合。

return string

ANSI 格式化字串的 HTML 表示形式

                public static function ansiToHtml($string, $styleMap = [])
{
    $styleMap = [
        // https://www.w3.org/TR/CSS2/syndata.html#value-def-color
        self::FG_BLACK => ['color' => 'black'],
        self::FG_BLUE => ['color' => 'blue'],
        self::FG_CYAN => ['color' => 'aqua'],
        self::FG_GREEN => ['color' => 'lime'],
        self::FG_GREY => ['color' => 'silver'],
        // https://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/
        // https://drafts.csswg.org/css-color/#valuedef-rebeccapurple
        self::FG_PURPLE => ['color' => 'rebeccapurple'],
        self::FG_RED => ['color' => 'red'],
        self::FG_YELLOW => ['color' => 'yellow'],
        self::BG_BLACK => ['background-color' => 'black'],
        self::BG_BLUE => ['background-color' => 'blue'],
        self::BG_CYAN => ['background-color' => 'aqua'],
        self::BG_GREEN => ['background-color' => 'lime'],
        self::BG_GREY => ['background-color' => 'silver'],
        self::BG_PURPLE => ['background-color' => 'rebeccapurple'],
        self::BG_RED => ['background-color' => 'red'],
        self::BG_YELLOW => ['background-color' => 'yellow'],
        self::BOLD => ['font-weight' => 'bold'],
        self::ITALIC => ['font-style' => 'italic'],
        self::UNDERLINE => ['text-decoration' => ['underline']],
        self::OVERLINED => ['text-decoration' => ['overline']],
        self::CROSSED_OUT => ['text-decoration' => ['line-through']],
        self::BLINK => ['text-decoration' => ['blink']],
        self::CONCEALED => ['visibility' => 'hidden'],
    ] + $styleMap;
    $tags = 0;
    $result = preg_replace_callback(
        '/\033\[([\d;]+)m/',
        function ($ansi) use (&$tags, $styleMap) {
            $style = [];
            $reset = false;
            $negative = false;
            foreach (explode(';', $ansi[1]) as $controlCode) {
                if ($controlCode == 0) {
                    $style = [];
                    $reset = true;
                } elseif ($controlCode == self::NEGATIVE) {
                    $negative = true;
                } elseif (isset($styleMap[$controlCode])) {
                    $style[] = $styleMap[$controlCode];
                }
            }
            $return = '';
            while ($reset && $tags > 0) {
                $return .= '</span>';
                $tags--;
            }
            if (empty($style)) {
                return $return;
            }
            $currentStyle = [];
            foreach ($style as $content) {
                $currentStyle = ArrayHelper::merge($currentStyle, $content);
            }
            // if negative is set, invert background and foreground
            if ($negative) {
                if (isset($currentStyle['color'])) {
                    $fgColor = $currentStyle['color'];
                    unset($currentStyle['color']);
                }
                if (isset($currentStyle['background-color'])) {
                    $bgColor = $currentStyle['background-color'];
                    unset($currentStyle['background-color']);
                }
                if (isset($fgColor)) {
                    $currentStyle['background-color'] = $fgColor;
                }
                if (isset($bgColor)) {
                    $currentStyle['color'] = $bgColor;
                }
            }
            $styleString = '';
            foreach ($currentStyle as $name => $value) {
                if (is_array($value)) {
                    $value = implode(' ', $value);
                }
                $styleString .= "$name: $value;";
            }
            $tags++;
            return "$return<span style=\"$styleString\">";
        },
        $string
    );
    while ($tags > 0) {
        $result .= '</span>';
        $tags--;
    }
    return $result;
}

            
beginAnsiFormat() public static method

定義於: yii\helpers\BaseConsole::beginAnsiFormat()

輸出 ANSI 格式代碼,該代碼會影響之後列印的任何文字的格式。

另請參閱

public static void beginAnsiFormat ( $format )
$format array

包含格式化值的陣列。您可以傳遞任何 FG_*BG_*TEXT_* 常數,以及 xtermFgColor()xtermBgColor() 來指定格式。

                public static function beginAnsiFormat($format)
{
    echo "\033[" . implode(';', $format) . 'm';
}

            
clearLine() public static method

定義於: yii\helpers\BaseConsole::clearLine()

清除游標目前所在的行,方法是傳送 ANSI 控制代碼 EL 並帶參數 2 給終端機。

游標位置將不會變更。

public static void clearLine ( )

                public static function clearLine()
{
    echo "\033[2K";
}

            
clearLineAfterCursor() public static method

定義於: yii\helpers\BaseConsole::clearLineAfterCursor()

透過傳送 ANSI 控制碼 EL 及參數 0 到終端機,清除從游標位置到行尾的文字。

游標位置將不會變更。

public static void clearLineAfterCursor ( )

                public static function clearLineAfterCursor()
{
    echo "\033[0K";
}

            
clearLineBeforeCursor() public static method

定義於: yii\helpers\BaseConsole::clearLineBeforeCursor()

透過傳送 ANSI 控制碼 EL 及參數 1 到終端機,清除從游標位置到行首的文字。

游標位置將不會變更。

public static void clearLineBeforeCursor ( )

                public static function clearLineBeforeCursor()
{
    echo "\033[1K";
}

            
clearScreen() public static method

定義於: yii\helpers\BaseConsole::clearScreen()

透過傳送 ANSI 控制碼 ED 及參數 2 到終端機,清除整個螢幕內容。

游標位置將不會變更。 注意: Windows 中使用的 ANSI.SYS 實作會將游標位置重設為螢幕的左上角。

public static void clearScreen ( )

                public static function clearScreen()
{
    echo "\033[2J";
}

            
clearScreenAfterCursor() public static method

定義於: yii\helpers\BaseConsole::clearScreenAfterCursor()

透過傳送 ANSI 控制碼 ED 及參數 0 到終端機,清除從游標位置到螢幕底端的文字。

游標位置將不會變更。

public static void clearScreenAfterCursor ( )

                public static function clearScreenAfterCursor()
{
    echo "\033[0J";
}

            
clearScreenBeforeCursor() public static method

定義於: yii\helpers\BaseConsole::clearScreenBeforeCursor()

透過傳送 ANSI 控制碼 ED 及參數 1 到終端機,清除從游標位置到螢幕頂端的文字。

游標位置將不會變更。

public static void clearScreenBeforeCursor ( )

                public static function clearScreenBeforeCursor()
{
    echo "\033[1J";
}

            
confirm() public static method

定義於: yii\helpers\BaseConsole::confirm()

要求使用者輸入 y 或 n 以確認。

典型的用法如下所示

if (Console::confirm("Are you sure?")) {
    echo "user typed yes\n";
} else {
    echo "user typed no\n";
}
public static boolean confirm ( $message, $default false )
$message string

在等待使用者輸入之前要輸出的訊息

$default boolean

如果未進行選擇,則傳回此值。

return boolean

使用者是否已確認

                public static function confirm($message, $default = false)
{
    while (true) {
        static::stdout($message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:');
        $input = trim(static::stdin());
        if (empty($input)) {
            return $default;
        }
        if (!strcasecmp($input, 'y') || !strcasecmp($input, 'yes')) {
            return true;
        }
        if (!strcasecmp($input, 'n') || !strcasecmp($input, 'no')) {
            return false;
        }
    }
}

            
endAnsiFormat() public static method

定義於: yii\helpers\BaseConsole::endAnsiFormat()

重設先前方法 beginAnsiFormat() 設定的任何 ANSI 格式。此後的任何輸出都將具有預設文字格式。

這等於呼叫。

echo Console::ansiFormatCode([Console::RESET])
public static void endAnsiFormat ( )

                public static function endAnsiFormat()
{
    echo "\033[0m";
}

            
endProgress() public static method

定義於: yii\helpers\BaseConsole::endProgress()

結束由 startProgress() 啟動的進度列。

另請參閱

public static void endProgress ( $remove false, $keepPrefix true )
$remove string|boolean

這可以是 false 以將進度列留在螢幕上,並僅列印換行符號。如果設定為 true,則會清除進度列的行。這也可以是要顯示以取代進度列的字串。

$keepPrefix boolean

當移除進度列時,是否保留為進度列指定的前綴。預設為 true。

                public static function endProgress($remove = false, $keepPrefix = true)
{
    if ($remove === false) {
        static::stdout(PHP_EOL);
    } else {
        if (static::streamSupportsAnsiColors(STDOUT)) {
            static::clearLine();
        }
        static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
    }
    flush();
    self::$_progressStart = null;
    self::$_progressWidth = null;
    self::$_progressPrefix = '';
    self::$_progressEta = null;
    self::$_progressEtaLastDone = 0;
    self::$_progressEtaLastUpdate = null;
}

            
error() public static method

定義於: yii\helpers\BaseConsole::error()

將文字列印到 STDERR,並附加歸位字元 (PHP_EOL)。

public static integer|boolean error ( $string null )
$string string|null

要列印的文字

return integer|boolean

列印的位元組數,或在錯誤時傳回 false。

                public static function error($string = null)
{
    return static::stderr($string . PHP_EOL);
}

            
errorSummary() public static method (available since version 2.0.14)

定義於: yii\helpers\BaseConsole::errorSummary()

產生驗證錯誤的摘要。

public static string errorSummary ( $models, $options = [] )
$models yii\base\Model|yii\base\Model[]

要顯示其驗證錯誤的模型。

$options array

以名稱-值對表示的標籤選項。以下選項會特別處理

  • showAllErrors: boolean, 如果設定為 true,則會顯示每個屬性的每個錯誤訊息,否則只會顯示每個屬性的第一個錯誤訊息。預設為 false
return string

產生的錯誤摘要

                public static function errorSummary($models, $options = [])
{
    $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
    $lines = self::collectErrors($models, $showAllErrors);
    return implode(PHP_EOL, $lines);
}

            
escape() public static method

定義於: yii\helpers\BaseConsole::escape()

跳脫 % 字元,使其在字串被 renderColoredString() 解析時不會被解釋為顏色代碼。

public static string escape ( $string )
$string string

要跳脫的字串

                public static function escape($string)
{
    // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
    return str_replace('%', '%%', $string);
}

            
getScreenSize() public static method

定義於: yii\helpers\BaseConsole::getScreenSize()

傳回終端機螢幕尺寸。

用法

list($width, $height) = ConsoleHelper::getScreenSize();
public static array|boolean getScreenSize ( $refresh false )
$refresh boolean

是否強制檢查且不重複使用快取的尺寸值。這對於在應用程式執行時偵測視窗尺寸變更很有用,但可能無法在每個終端機上取得最新的值。

return array|boolean

($width, $height) 的陣列,或在無法判斷尺寸時傳回 false。

                public static function getScreenSize($refresh = false)
{
    static $size;
    static $execDisabled;
    if ($size !== null && ($execDisabled || !$refresh)) {
        return $size;
    }
    if ($execDisabled === null) {
        $execDisabled = !function_exists('ini_get') || preg_match('/(\bexec\b)/i', ini_get('disable_functions'));
        if ($execDisabled) {
            return $size = false;
        }
    }
    if (static::isRunningOnWindows()) {
        $output = [];
        exec('mode con', $output);
        if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
            return $size = [(int) preg_replace('~\D~', '', $output[4]), (int) preg_replace('~\D~', '', $output[3])];
        }
    } else {
        // try stty if available
        $stty = [];
        if (exec('stty -a 2>&1', $stty)) {
            $stty = implode(' ', $stty);
            // Linux stty output
            if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) {
                return $size = [(int) $matches[2], (int) $matches[1]];
            }
            // MacOS stty output
            if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) {
                return $size = [(int) $matches[2], (int) $matches[1]];
            }
        }
        // fallback to tput, which may not be updated on terminal resize
        if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
            return $size = [$width, $height];
        }
        // fallback to ENV variables, which may not be updated on terminal resize
        if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
            return $size = [$width, $height];
        }
    }
    return $size = false;
}

            
hideCursor() public static method

定義於: yii\helpers\BaseConsole::hideCursor()

透過傳送 ANSI DECTCEM 代碼 ?25l 給終端機來隱藏游標。

使用 showCursor() 將其帶回。請勿忘記在您的應用程式結束時顯示游標。游標在結束後可能會保持隱藏在終端機中。

public static void hideCursor ( )

                public static function hideCursor()
{
    echo "\033[?25l";
}

            
input() public static method

定義於: yii\helpers\BaseConsole::input()

要求使用者輸入。當使用者輸入歸位字元 (PHP_EOL) 時結束。可選地,它也提供提示字元。

public static string input ( $prompt null )
$prompt string|null

在等待輸入之前要顯示的提示字元 (選用)

return string

使用者輸入

                public static function input($prompt = null)
{
    if (isset($prompt)) {
        static::stdout($prompt);
    }
    return static::stdin();
}

            
isRunningOnWindows() public static method

定義於: yii\helpers\BaseConsole::isRunningOnWindows()

如果主控台在 Windows 上執行,則傳回 true。

public static boolean isRunningOnWindows ( )

                public static function isRunningOnWindows()
{
    return DIRECTORY_SEPARATOR === '\\';
}

            
markdownToAnsi() public static method

定義於: yii\helpers\BaseConsole::markdownToAnsi()

透過套用一些 ANSI 格式,將 Markdown 轉換為在主控台環境中更易於閱讀的形式。

public static string markdownToAnsi ( $markdown )
$markdown string

Markdown 字串。

return string

解析結果為 ANSI 格式化字串。

                public static function markdownToAnsi($markdown)
{
    $parser = new ConsoleMarkdown();
    return $parser->parse($markdown);
}

            
moveCursorBackward() public static method

定義於: yii\helpers\BaseConsole::moveCursorBackward()

透過傳送 ANSI 控制代碼 CUB 給終端機,將終端機游標向後移動。

如果游標已在螢幕邊緣,則此操作無效。

public static void moveCursorBackward ( $steps 1 )
$steps integer

游標應向後移動的步數

                public static function moveCursorBackward($steps = 1)
{
    echo "\033[" . (int) $steps . 'D';
}

            
moveCursorDown() public static method

定義於: yii\helpers\BaseConsole::moveCursorDown()

透過傳送 ANSI 控制代碼 CUD 給終端機,將終端機游標向下移動。

如果游標已在螢幕邊緣,則此操作無效。

public static void moveCursorDown ( $rows 1 )
$rows integer

游標應向下移動的列數

                public static function moveCursorDown($rows = 1)
{
    echo "\033[" . (int) $rows . 'B';
}

            
moveCursorForward() public static method

定義於: yii\helpers\BaseConsole::moveCursorForward()

透過傳送 ANSI 控制代碼 CUF 給終端機,將終端機游標向前移動。

如果游標已在螢幕邊緣,則此操作無效。

public static void moveCursorForward ( $steps 1 )
$steps integer

游標應向前移動的步數

                public static function moveCursorForward($steps = 1)
{
    echo "\033[" . (int) $steps . 'C';
}

            
moveCursorNextLine() public static method

定義於: yii\helpers\BaseConsole::moveCursorNextLine()

透過傳送 ANSI 控制代碼 CNL 給終端機,將終端機游標移動到下一行的開頭。

public static void moveCursorNextLine ( $lines 1 )
$lines integer

游標應向下移動的行數

                public static function moveCursorNextLine($lines = 1)
{
    echo "\033[" . (int) $lines . 'E';
}

            
moveCursorPrevLine() public static method

定義於: yii\helpers\BaseConsole::moveCursorPrevLine()

透過傳送 ANSI 控制代碼 CPL 給終端機,將終端機游標移動到上一行的開頭。

public static void moveCursorPrevLine ( $lines 1 )
$lines integer

游標應向上移動的行數

                public static function moveCursorPrevLine($lines = 1)
{
    echo "\033[" . (int) $lines . 'F';
}

            
moveCursorTo() public static method

定義於: yii\helpers\BaseConsole::moveCursorTo()

透過傳送 ANSI 控制代碼 CUP 或 CHA 給終端機,將游標移動到以欄和列給定的絕對位置。

public static void moveCursorTo ( $column, $row null )
$column integer

基於 1 的欄號,1 為螢幕的最左邊緣。

$row integer|null

基於 1 的列號,1 為螢幕的最上邊緣。如果未設定,游標將僅在目前行中移動。

                public static function moveCursorTo($column, $row = null)
{
    if ($row === null) {
        echo "\033[" . (int) $column . 'G';
    } else {
        echo "\033[" . (int) $row . ';' . (int) $column . 'H';
    }
}

            
moveCursorUp() public static method

定義於: yii\helpers\BaseConsole::moveCursorUp()

透過傳送 ANSI 控制代碼 CUU 給終端機,將終端機游標向上移動。

如果游標已在螢幕邊緣,則此操作無效。

public static void moveCursorUp ( $rows 1 )
$rows integer

游標應向上移動的列數

                public static function moveCursorUp($rows = 1)
{
    echo "\033[" . (int) $rows . 'A';
}

            
output() public static method

定義於: yii\helpers\BaseConsole::output()

將文字列印到 STDOUT,並附加歸位字元 (PHP_EOL)。

public static integer|boolean output ( $string null )
$string string|null

要列印的文字

return integer|boolean

列印的位元組數,或在錯誤時傳回 false。

                public static function output($string = null)
{
    return static::stdout($string . PHP_EOL);
}

            
prompt() public static method

定義於: yii\helpers\BaseConsole::prompt()

提示使用者輸入並驗證輸入。

public static string prompt ( $text, $options = [] )
$text string

提示字串

$options array

驗證輸入的選項

  • required: 是否為必填
  • default: 如果使用者未輸入內容時的預設值
  • pattern: 驗證使用者輸入的正規表示式模式
  • validator: 用於驗證輸入的可呼叫函式。該函式必須接受兩個參數
  • input: 要驗證的使用者輸入
  • error: 驗證失敗時,以引用方式傳遞的錯誤值。
return string

使用者輸入

                public static function prompt($text, $options = [])
{
    $options = ArrayHelper::merge(
        [
            'required' => false,
            'default' => null,
            'pattern' => null,
            'validator' => null,
            'error' => 'Invalid input.',
        ],
        $options
    );
    $error = null;
    top:
    $input = $options['default']
        ? static::input("$text [" . $options['default'] . '] ')
        : static::input("$text ");
    if ($input === '') {
        if (isset($options['default'])) {
            $input = $options['default'];
        } elseif ($options['required']) {
            static::output($options['error']);
            goto top;
        }
    } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
        static::output($options['error']);
        goto top;
    } elseif ($options['validator'] && !call_user_func_array($options['validator'], [$input, &$error])) {
        static::output(isset($error) ? $error : $options['error']);
        goto top;
    }
    return $input;
}

            
renderColoredString() public static method

定義於: yii\helpers\BaseConsole::renderColoredString()

透過將像 %y (代表黃色) 這樣的模式替換為 ANSI 控制代碼,將字串轉換為 ANSI 格式。

使用幾乎與 https://github.com/pear/Console_Color2/blob/master/Console/Color2.php 相同的語法。轉換表為:(在某些終端機上,'bold' 意為 'light')。它幾乎與 irssi 使用的轉換表相同。

             text      text            background
 ------------------------------------------------
 %k %K %0    black     dark grey       black
 %r %R %1    red       bold red        red
 %g %G %2    green     bold green      green
 %y %Y %3    yellow    bold yellow     yellow
 %b %B %4    blue      bold blue       blue
 %m %M %5    magenta   bold magenta    magenta
 %p %P       magenta (think: purple)
 %c %C %6    cyan      bold cyan       cyan
 %w %W %7    white     bold white      white

 %F     Blinking, Flashing
 %U     Underline
 %8     Reverse
 %_,%9  Bold

 %n     Resets the color
 %%     A single %

第一個參數是要轉換的字串,第二個參數是顏色是否應被使用的可選旗標。預設為 true,如果設定為 false,顏色代碼將被移除(且 %% 將轉換為 %)

public static string renderColoredString ( $string, $colored true )
$string string

要轉換的字串

$colored boolean

字串是否應著色?

                public static function renderColoredString($string, $colored = true)
{
    // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
    static $conversions = [
        '%y' => [self::FG_YELLOW],
        '%g' => [self::FG_GREEN],
        '%b' => [self::FG_BLUE],
        '%r' => [self::FG_RED],
        '%p' => [self::FG_PURPLE],
        '%m' => [self::FG_PURPLE],
        '%c' => [self::FG_CYAN],
        '%w' => [self::FG_GREY],
        '%k' => [self::FG_BLACK],
        '%n' => [0], // reset
        '%Y' => [self::FG_YELLOW, self::BOLD],
        '%G' => [self::FG_GREEN, self::BOLD],
        '%B' => [self::FG_BLUE, self::BOLD],
        '%R' => [self::FG_RED, self::BOLD],
        '%P' => [self::FG_PURPLE, self::BOLD],
        '%M' => [self::FG_PURPLE, self::BOLD],
        '%C' => [self::FG_CYAN, self::BOLD],
        '%W' => [self::FG_GREY, self::BOLD],
        '%K' => [self::FG_BLACK, self::BOLD],
        '%N' => [0, self::BOLD],
        '%3' => [self::BG_YELLOW],
        '%2' => [self::BG_GREEN],
        '%4' => [self::BG_BLUE],
        '%1' => [self::BG_RED],
        '%5' => [self::BG_PURPLE],
        '%6' => [self::BG_CYAN],
        '%7' => [self::BG_GREY],
        '%0' => [self::BG_BLACK],
        '%F' => [self::BLINK],
        '%U' => [self::UNDERLINE],
        '%8' => [self::NEGATIVE],
        '%9' => [self::BOLD],
        '%_' => [self::BOLD],
    ];
    if ($colored) {
        $string = str_replace('%%', '% ', $string);
        foreach ($conversions as $key => $value) {
            $string = str_replace(
                $key,
                static::ansiFormatCode($value),
                $string
            );
        }
        $string = str_replace('% ', '%', $string);
    } else {
        $string = preg_replace('/%((%)|.)/', '$2', $string);
    }
    return $string;
}

            
restoreCursorPosition() public static method

定義於: yii\helpers\BaseConsole::restoreCursorPosition()

透過傳送 ANSI 控制代碼 RCP 給終端機,還原使用 saveCursorPosition() 儲存的游標位置。

public static void restoreCursorPosition ( )

                public static function restoreCursorPosition()
{
    echo "\033[u";
}

            
saveCursorPosition() public static method

定義於: yii\helpers\BaseConsole::saveCursorPosition()

透過傳送 ANSI 控制代碼 SCP 給終端機,儲存目前的游標位置。

位置隨後可以使用 restoreCursorPosition() 還原。

public static void saveCursorPosition ( )

                public static function saveCursorPosition()
{
    echo "\033[s";
}

            
scrollDown() public static method

定義於: yii\helpers\BaseConsole::scrollDown()

透過傳送 ANSI 控制代碼 SD 給終端機,將整個頁面向下捲動。

新行會被加到頂部。ANSI.SYS 在 windows 中不支援此功能。

public static void scrollDown ( $lines 1 )
$lines integer

向下捲動的行數

                public static function scrollDown($lines = 1)
{
    echo "\033[" . (int) $lines . 'T';
}

            
scrollUp() public static method

定義於: yii\helpers\BaseConsole::scrollUp()

透過傳送 ANSI 控制代碼 SU 給終端機,將整個頁面向上捲動。

新行會被加到底部。ANSI.SYS 在 windows 中不支援此功能。

public static void scrollUp ( $lines 1 )
$lines integer

向上捲動的行數

                public static function scrollUp($lines = 1)
{
    echo "\033[" . (int) $lines . 'S';
}

            
select() public static method

定義於: yii\helpers\BaseConsole::select()

提供使用者從選項中選擇。輸入 '?' 將顯示選項列表及其說明。

public static string select ( $prompt, $options = [], $default null )
$prompt string

提示訊息

$options array

要選擇的選項的鍵值陣列。鍵是輸入和使用的內容,值是幫助命令向終端使用者顯示的內容。

$default string|null

當使用者未提供選項時要使用的值。如果預設值為 null,則使用者必須選擇一個選項。

return string

使用者選擇的選項字元

版本 描述
2.0.49 新增了 $default 參數

                public static function select($prompt, $options = [], $default = null)
{
    top:
    static::stdout("$prompt (" . implode(',', array_keys($options)) . ',?)'
        . ($default !== null ? '[' . $default . ']' : '') . ': ');
    $input = static::stdin();
    if ($input === '?') {
        foreach ($options as $key => $value) {
            static::output(" $key - $value");
        }
        static::output(' ? - Show help');
        goto top;
    } elseif ($default !== null && $input === '') {
        return $default;
    } elseif (!array_key_exists($input, $options)) {
        goto top;
    }
    return $input;
}

            
showCursor() public static method

定義於: yii\helpers\BaseConsole::showCursor()

當游標被 hideCursor() 隱藏時,透過傳送 ANSI DECTCEM 代碼 ?25h 給終端機,再次顯示游標。

public static void showCursor ( )

                public static function showCursor()
{
    echo "\033[?25h";
}

            
startProgress() public static method

定義於: yii\helpers\BaseConsole::startProgress()

開始在螢幕上顯示進度列。

此進度條將由 updateProgress() 更新,並可能由 endProgress() 結束。

以下範例展示了進度條的簡單用法

Console::startProgress(0, 1000);
for ($n = 1; $n <= 1000; $n++) {
    usleep(1000);
    Console::updateProgress($n, 1000);
}
Console::endProgress();

類似 Git clone 的進度(僅顯示狀態資訊)

Console::startProgress(0, 1000, 'Counting objects: ', false);
for ($n = 1; $n <= 1000; $n++) {
    usleep(1000);
    Console::updateProgress($n, 1000);
}
Console::endProgress("done." . PHP_EOL);

另請參閱

public static void startProgress ( $done, $total, $prefix '', $width null )
$done integer

已完成的項目數量。

$total integer

要完成的項目總值。

$prefix string

要在進度條之前顯示的可選字串。預設為空字串,表示不顯示任何前綴。

$width integer|float|boolean|null

進度條的可選寬度。這可以是代表進度條顯示字元數的整數,也可以是介於 0 和 1 之間的浮點數,代表進度條可能佔用的螢幕百分比。也可以設定為 false 以停用進度條,僅顯示進度資訊,例如百分比、項目數量和 ETA。如果未設定,進度條將與螢幕一樣寬。螢幕尺寸將使用 getScreenSize() 偵測。

                public static function startProgress($done, $total, $prefix = '', $width = null)
{
    self::$_progressStart = time();
    self::$_progressWidth = $width;
    self::$_progressPrefix = $prefix;
    self::$_progressEta = null;
    self::$_progressEtaLastDone = 0;
    self::$_progressEtaLastUpdate = time();
    static::updateProgress($done, $total);
}

            
stderr() public static method

定義於: yii\helpers\BaseConsole::stderr()

將字串列印到 STDERR。

public static integer|boolean stderr ( $string )
$string string

要列印的字串

return integer|boolean

列印的位元組數,錯誤時為 false

                public static function stderr($string)
{
    return fwrite(\STDERR, $string);
}

            
stdin() public static method

定義於: yii\helpers\BaseConsole::stdin()

從 STDIN 取得輸入,並傳回已修剪尾端 EOL 字元的字串。

public static string stdin ( $raw false )
$raw boolean

如果設定為 true,則傳回未經修剪的原始字串

return string

從 stdin 讀取的字串

                public static function stdin($raw = false)
{
    return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL);
}

            
stdout() public static method

定義於: yii\helpers\BaseConsole::stdout()

將字串列印到 STDOUT。

public static integer|boolean stdout ( $string )
$string string

要列印的字串

return integer|boolean

列印的位元組數,錯誤時為 false

                public static function stdout($string)
{
    return fwrite(\STDOUT, $string);
}

            
streamSupportsAnsiColors() public static method

定義於: yii\helpers\BaseConsole::streamSupportsAnsiColors()

如果資料流支援色彩化,則傳回 true。如果資料流不支援 ANSI 顏色,則會停用 ANSI 顏色。

  • 沒有 ansicon 的 windows
  • 非 tty 主控台
public static boolean streamSupportsAnsiColors ( $stream )
$stream mixed
return boolean

如果串流支援 ANSI 顏色,則為 True,否則為 false。

                public static function streamSupportsAnsiColors($stream)
{
    return DIRECTORY_SEPARATOR === '\\'
        ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
        : function_exists('posix_isatty') && @posix_isatty($stream);
}

            
stripAnsiFormat() public static method

定義於: yii\helpers\BaseConsole::stripAnsiFormat()

從字串中移除 ANSI 控制代碼。

public static string stripAnsiFormat ( $string )
$string string

要移除的字串

                public static function stripAnsiFormat($string)
{
    return preg_replace(self::ansiCodesPattern(), '', (string)$string);
}

            
updateProgress() public static method

定義於: yii\helpers\BaseConsole::updateProgress()

更新由 startProgress() 啟動的進度列。

另請參閱

public static void updateProgress ( $done, $total, $prefix null )
$done integer

已完成的項目數量。

$total integer

要完成的項目總值。

$prefix string|null

要在進度條之前顯示的可選字串。預設為 null,表示將使用 startProgress() 指定的前綴。如果指定了前綴,它將更新稍後呼叫將使用的前綴。

                public static function updateProgress($done, $total, $prefix = null)
{
    if ($prefix === null) {
        $prefix = self::$_progressPrefix;
    } else {
        self::$_progressPrefix = $prefix;
    }
    $width = static::getProgressbarWidth($prefix);
    $percent = ($total == 0) ? 1 : $done / $total;
    $info = sprintf('%d%% (%d/%d)', $percent * 100, $done, $total);
    self::setETA($done, $total);
    $info .= self::$_progressEta === null ? ' ETA: n/a' : sprintf(' ETA: %d sec.', self::$_progressEta);
    // Number extra characters outputted. These are opening [, closing ], and space before info
    // Since Windows uses \r\n\ for line endings, there's one more in the case
    $extraChars = static::isRunningOnWindows() ? 4 : 3;
    $width -= $extraChars + static::ansiStrlen($info);
    // skipping progress bar on very small display or if forced to skip
    if ($width < 5) {
        static::stdout("\r$prefix$info   ");
    } else {
        if ($percent < 0) {
            $percent = 0;
        } elseif ($percent > 1) {
            $percent = 1;
        }
        $bar = floor($percent * $width);
        $status = str_repeat('=', $bar);
        if ($bar < $width) {
            $status .= '>';
            $status .= str_repeat(' ', $width - $bar - 1);
        }
        static::stdout("\r$prefix" . "[$status] $info");
    }
    flush();
}

            
wrapText() public static method (自版本 2.0.4 起可用)

定義於: yii\helpers\BaseConsole::wrapText()

自動換行文字,並加上縮排以符合螢幕尺寸。

如果無法偵測到螢幕尺寸,或者縮排大於螢幕尺寸,則文字將不會被換行。

第一行將不會被縮排,因此給定螢幕寬度為 16 個字元,Console::wrapText("Lorem ipsum dolor sit amet.", 4) 將產生以下輸出

Lorem ipsum
    dolor sit
    amet.
public static string wrapText ( $text, $indent 0, $refresh false )
$text string

要換行的文字

$indent integer

用於縮排的空格數。

$refresh boolean

是否強制重新整理螢幕尺寸。這將傳遞給 getScreenSize()

return string

換行後的文字。

                public static function wrapText($text, $indent = 0, $refresh = false)
{
    $size = static::getScreenSize($refresh);
    if ($size === false || $size[0] <= $indent) {
        return $text;
    }
    $pad = str_repeat(' ', $indent);
    $lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n"));
    $first = true;
    foreach ($lines as $i => $line) {
        if ($first) {
            $first = false;
            continue;
        }
        $lines[$i] = $pad . $line;
    }
    return implode("\n", $lines);
}

            
xtermBgColor() public static method

定義於: yii\helpers\BaseConsole::xtermBgColor()

傳回 xterm 背景顏色的 ANSI 格式代碼。

您可以將此方法的傳回值傳遞給其中一種格式化方法:ansiFormat()ansiFormatCode()beginAnsiFormat()

另請參閱 https://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors

public static string xtermBgColor ( $colorCode )
$colorCode integer

Xterm 顏色代碼

                public static function xtermBgColor($colorCode)
{
    return '48;5;' . $colorCode;
}

            
xtermFgColor() public static method

定義於: yii\helpers\BaseConsole::xtermFgColor()

傳回 xterm 前景顏色的 ANSI 格式代碼。

您可以將此方法的傳回值傳遞給其中一種格式化方法:ansiFormat()ansiFormatCode()beginAnsiFormat()

另請參閱 https://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors

public static string xtermFgColor ( $colorCode )
$colorCode integer

Xterm 顏色代碼

                public static function xtermFgColor($colorCode)
{
    return '38;5;' . $colorCode;
}