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() 開始位置と長さのパラメータで指定された文字列の、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() saveCursorPosition() で保存されたカーソル位置を、ANSI制御コードRCPを端末に送信して復元します。 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カラーが無効になります。 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()

開始位置と長さのパラメータで指定された文字列の、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 (バージョン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

FG_COLORまたはBOLDのようなANSI制御コードから一連の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 メソッド

定義場所: yii\helpers\BaseConsole::clearScreenAfterCursor()

カーソルから画面の末尾までのテキストを、ANSI制御コードEDに引数0を指定して端末に送信することでクリアします。

カーソルの位置は変更されません。

public static void clearScreenAfterCursor ( )

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

            
clearScreenBeforeCursor() public static メソッド

定義場所: yii\helpers\BaseConsole::clearScreenBeforeCursor()

カーソルから画面の先頭までのテキストを、ANSI制御コードEDに引数1を指定して端末に送信することでクリアします。

カーソルの位置は変更されません。

public static void clearScreenBeforeCursor ( )

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

            
confirm() public static メソッド

定義場所: 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 メソッド

定義場所: 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 メソッド

定義場所: 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 メソッド

定義場所: yii\helpers\BaseConsole::error()

キャリッジリターン(PHP_EOL)を付加してテキストをSTDERRに出力します。

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 メソッド (バージョン 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 メソッド

定義場所: 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 メソッド

定義場所: 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 メソッド

定義場所: yii\helpers\BaseConsole::hideCursor()

ANSI DECTCEMコード ?25l を端末に送信してカーソルを非表示にします。

カーソルを戻すにはshowCursor()を使用してください。アプリケーションの終了時にカーソルを表示することを忘れないでください。終了後もターミナルでカーソルが非表示のままになる可能性があります。

public static void hideCursor ( )

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

            
input() public static メソッド

定義場所: 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 メソッド

定義場所: yii\helpers\BaseConsole::isRunningOnWindows()

コンソールがWindows上で実行されている場合はtrueを返します。

public static boolean isRunningOnWindows ( )

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

            
markdownToAnsi() public static メソッド

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

いくつかのANSIフォーマットを適用することにより、コンソール環境で読みやすくするためにMarkdownを変換します。

public static string markdownToAnsi ( $markdown )
$markdown string

マークダウン文字列。

return string

ANSI形式でフォーマットされた解析結果の文字列。

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

            
moveCursorBackward() public static メソッド

定義元: 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 メソッド

定義元: 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 メソッド

定義元: 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 メソッド

定義元: 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 メソッド

定義元: 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 メソッド

定義元: 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 メソッド

定義元: 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 メソッド

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

キャリッジリターン(PHP_EOL)を付加してテキストをSTDOUTに出力します。

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 メソッド

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

ユーザに入力を促し、それを検証します。

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

プロンプト文字列

$options array

入力を検証するためのオプション

  • required: 必須かどうか
  • default: ユーザーが何も入力しなかった場合のデフォルト値
  • pattern: ユーザー入力を検証するための正規表現パターン
  • validator: 入力を検証するための呼び出し可能な関数。関数は2つのパラメータを受け入れる必要があります
  • 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 メソッド

定義元: 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 %

最初のパラメータは変換する文字列、2番目のパラメータは色を使用するかどうかのオプションフラグです。デフォルトは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()

saveCursorPosition() で保存されたカーソル位置を、ANSI制御コードRCPを端末に送信して復元します。

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を端末に送信して、ページ全体を下にスクロールします。

新しい行は上に追加されます。これは、Windowsで使用されるANSI.SYSではサポートされていません。

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を端末に送信して、ページ全体を上にスクロールします。

新しい行は下に追加されます。これは、Windowsで使用されるANSI.SYSではサポートされていません。

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クローンのような進捗状況(ステータス情報のみを表示)

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カラーが無効になります。

  • ansiconなしのWindows
  • ttyコンソールではない
public static boolean streamSupportsAnsiColors ( $stream )
$stream 混合型
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 メソッド

定義元: 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 メソッド

定義元: 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 メソッド (バージョン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 メソッド

定義元: 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 メソッド

定義元: 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;
}