0 追蹤者

類別 yii\helpers\BaseConsole

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

BaseConsole 為 yii\helpers\Console 提供了具體的實作。

請勿使用 BaseConsole。請改用 yii\helpers\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() 將文字附加換行符號 (PHP_EOL) 後列印到 STDERR。 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() 將文字附加換行符號 (PHP_EOL) 後列印到 STDOUT。 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 取得輸入,並傳回已修剪 EOLs 的字串。 yii\helpers\BaseConsole
stdout() 將字串列印到 STDOUT。 yii\helpers\BaseConsole
streamSupportsAnsiColors() 如果流支援色彩化,則傳回 true。如果流不支援,則會停用 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

傳回字串中由 start 和 length 參數指定,帶有 ANSI 彩色碼的部分。

如果字串具有顏色碼,則將傳回 "TEXT_COLOR + TEXT_STRING + DEFAULT_COLOR",否則將只是簡單的 "TEXT_STRING"。

public static string ansiColorizedSubstr ( $string, $start, $length )
$string 字串
$start 整數
$length 整數

                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

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

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

要格式化的字串

$format 陣列

包含格式化值的陣列。您可以傳遞任何 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

傳回 ANSI 格式碼。

public static string ansiFormatCode ( $format )
$format 陣列

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

傳回 字串

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

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

            
ansiStrlen() public static method

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

public static integer ansiStrlen ( $string )
$string 字串

要測量的字串

傳回 整數

不計算 ANSI 格式字元的字串長度

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

            
ansiStrwidth() public static method (自 2.0.36 版本起可用)

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

public static integer ansiStrwidth ( $string )
$string 字串

要測量的字串

傳回 整數

不計算 ANSI 格式字元的字串寬度

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

            
ansiToHtml() public static method

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

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

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

要轉換的字串。

$styleMap 陣列

ANSI 控制碼 (例如 FG_COLORBOLD) 到一組 CSS 樣式定義的可選對應。CSS 樣式定義表示為陣列,其中陣列鍵對應於 CSS 樣式屬性名稱,值為 CSS 值。值可以是將合併並以 ' ' 呈現時內爆的陣列。

傳回 字串

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

輸出一個 ANSI 格式碼,會影響之後列印的所有文字的格式。

參見

public static void beginAnsiFormat ( $format )
$format 陣列

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

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

            
clearLine() public static method

透過傳送 ANSI 控制碼 EL 及參數 2 到終端機,清除游標目前所在的行。

游標位置將不會變更。

public static void clearLine ( )

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

            
clearLineAfterCursor() public static method

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

游標位置將不會變更。

public static void clearLineAfterCursor ( )

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

            
clearLineBeforeCursor() public static method

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

游標位置將不會變更。

public static void clearLineBeforeCursor ( )

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

            
clearScreen() public static method

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

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

public static void clearScreen ( )

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

            
clearScreenAfterCursor() public static method

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

游標位置將不會變更。

public static void clearScreenAfterCursor ( )

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

            
clearScreenBeforeCursor() public static method

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

游標位置將不會變更。

public static void clearScreenBeforeCursor ( )

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

            
confirm() public static method

詢問使用者輸入 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 字串

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

$default 布林值

如果沒有做出選擇,則傳回此值。

傳回 布林值

使用者是否確認

                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

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

這等於呼叫:

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

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

            
endProgress() public static method

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

參見

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

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

$keepPrefix 布林值

是否在移除進度條時保留為進度條指定的前綴。預設為 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

將文字附加換行符號 (PHP_EOL) 後列印到 STDERR。

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

要列印的文字

傳回 integer|boolean

列印的位元組數,如果發生錯誤則為 false。

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

            
errorSummary() public static method (自 2.0.14 版本起可用)

產生驗證錯誤的摘要。

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

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

$options 陣列

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

  • showAllErrors: 布林值,如果設定為 true,則會顯示每個屬性的每個錯誤訊息,否則只會顯示每個屬性的第一個錯誤訊息。預設值為 false
傳回 字串

產生的錯誤摘要

                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

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

public static string escape ( $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

傳回終端機螢幕尺寸。

用法

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

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

傳回 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

透過傳送 ANSI DECTCEM 碼 ?25l 到終端機,隱藏游標。

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

public static void hideCursor ( )

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

            
input() public static method

要求使用者輸入。當使用者輸入換行符號 (PHP_EOL) 時結束。可選地,它也提供提示字串。

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

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

傳回 字串

使用者的輸入

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

            
isRunningOnWindows() public static method

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

public static boolean isRunningOnWindows ( )

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

            
markdownToAnsi() public static method

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

public static string markdownToAnsi ( $markdown )
$markdown 字串

markdown 字串。

傳回 字串

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

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

            
moveCursorBackward() public static method

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

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

public static void moveCursorBackward ( $steps 1 )
$steps 整數

游標應向後移動的步數

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

            
moveCursorDown() public static method

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

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

public static void moveCursorDown ( $rows 1 )
$rows 整數

游標應向下移動的列數

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

            
moveCursorForward() public static method

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

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

public static void moveCursorForward ( $steps 1 )
$steps 整數

游標應向前移動的步數

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

            
moveCursorNextLine() public static method

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

public static void moveCursorNextLine ( $lines 1 )
$lines 整數

游標應向下移動的行數

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

            
moveCursorPrevLine() public static method

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

public static void moveCursorPrevLine ( $lines 1 )
$lines 整數

游標應向上移動的行數

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

            
moveCursorTo() public static method

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

public static void moveCursorTo ( $column, $row null )
$column 整數

基於 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

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

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

public static void moveCursorUp ( $rows 1 )
$rows 整數

游標應向上移動的列數

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

            
output() public static method

將文字附加換行符號 (PHP_EOL) 後列印到 STDOUT。

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

要列印的文字

傳回 integer|boolean

列印的位元組數,如果發生錯誤則為 false。

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

            
prompt() public static method

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

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

提示字串

$options 陣列

驗證輸入的選項

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

使用者輸入

                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

透過將 %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 字串

要轉換的字串

$colored 布林值

字串是否應著色?

                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

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

public static void restoreCursorPosition ( )

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

            
saveCursorPosition() public static method

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

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

public static void saveCursorPosition ( )

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

            
scrollDown() public static method

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

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

public static void scrollDown ( $lines 1 )
$lines 整數

向下捲動的行數

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

            
scrollUp() public static method

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

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

public static void scrollUp ( $lines 1 )
$lines 整數

向上捲動的行數

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

            
select() public static method

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

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

提示訊息

$options 陣列

要從中選擇的選項的鍵值陣列。鍵是輸入和使用的內容,值是透過 help 命令顯示給終端使用者的內容。

$default string|null

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

傳回 字串

使用者選擇的選項字元

版本 描述
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

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

public static void showCursor ( )

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

            
startProgress() public static method

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

此進度條將由 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 整數

已完成的項目數。

$total 整數

要完成的項目總數。

$prefix 字串

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

$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

將字串列印到 STDERR。

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

要列印的字串

傳回 integer|boolean

列印的位元組數,如果發生錯誤則為 false

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

            
stdin() public static method

從 STDIN 取得輸入,並傳回已修剪 EOLs 的字串。

public static string stdin ( $raw false )
$raw 布林值

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

傳回 字串

從 stdin 讀取的字串

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

            
stdout() public static method

將字串列印到 STDOUT。

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

要列印的字串

傳回 integer|boolean

列印的位元組數,如果發生錯誤則為 false

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

            
streamSupportsAnsiColors() public static method

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

  • 沒有 ansicon 的 Windows
  • 非 tty 主控台
public static boolean streamSupportsAnsiColors ( $stream )
$stream mixed
傳回 布林值

如果串流支援 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

從字串中移除 ANSI 控制碼。

public static string stripAnsiFormat ( $string )
$string 字串

要移除 ANSI 格式的字串

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

            
updateProgress() public static method

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

參見

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

已完成的項目數。

$total 整數

要完成的項目總數。

$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 (available since version 2.0.4)

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

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

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

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

要換行的文字

$indent 整數

用於縮排的空格數。

$refresh 布林值

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

傳回 字串

換行後的文字。

                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

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

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

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

public static string xtermBgColor ( $colorCode )
$colorCode 整數

Xterm 顏色代碼

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

            
xtermFgColor() public static method

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

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

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

public static string xtermFgColor ( $colorCode )
$colorCode 整數

Xterm 顏色代碼

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