助手类

未匹配的标注

助手类

Yii 提供了许多类,可以帮助简化常见的编码任务,比如字符串或数组操作、HTML代码生成等。这些助手类被组织在 yii\helpers 命名空间下,并且都是静态类,这意味着它们只包含静态属性和方法,不应该被实例化。

你可以直接调用一个助手类的静态方法,如下所示:

use yii\helpers\Html;

echo Html::encode('Test > test');

注意:为了支持自定义助手类,Yii 将每个核心助手类分解为两个类,一个基类(如BaseArrayHelper)和一个具体类(如 ArrayHelper)。当您使用助手时,应该只使用具体版本,而不要使用基类。

核心助手类

Yii 版本中提供了以下核心助手类:

ArrayHelper

除了丰富的 PHP 数组函数集 之外,Yii 的数组助手类,还提供了额外的静态方法,使您能够更有效地处理数组。

ArrayHelper::toArray

通常情况下,您可能需要将对象或对象数组转换为数组。最常见的情况,是转换活动记录模型,以便通过 REST API 来服务于数据数组,或者以其他方式使用它。下面的代码可以用来做这件事:

$posts = Post::find()->limit(10)->all();
$data = ArrayHelper::toArray($posts, [
    'app\models\Post' => [
        'id',
        'title',
        // the key name in array result => property name
        'createTime' => 'created_at',
        // the key name in array result => anonymous function
        'length' => function ($post) {
            return strlen($post->content);
        },
    ],
]);

第一个参数,包含我们想要转换的数据,在此例中,我们需要转换一个 Post AR 模型。
第二个参数,是每个类的转换映射,在此例中,我们正在为 Post 模型设置一个映射,每个映射数组包含一组映射,每个映射可以是:

  • 要包含的字段名
  • 所需的数组键名和要从中获取值的模型列名的键-值对。
  • 所需数组键名的键值对和返回值的回调函数。

以上对单个模型的换算结果为:

[
    'id' => 123,
    'title' => 'test',
    'createTime' => '2013-01-01 12:00AM',
    'length' => 301,
]

通过在类中实现 yii\base\Arrayable 接口,可以为特定类提供将对象转换为数组的默认方式。

ArrayHelper::merge

你可以使用 yii\helpers\ArrayHelper::merge() 来递归地合并两个或多个数组。如果每个数组都有一个具有相同字符串键值的元素,则后者将覆盖前者,这一点与 PHP 数组函数 array_merge_recursive() 不同。如果两个数组都有一个数组类型的元素并且具有相同的键值,则将进行递归合并。对于整型键元素,后一个数组中的元素将被追加到前一个数组中。

你可以使用 yii\helpers\UnsetArrayValue 对象来取消先前数组中的值,或者 yii\helpers\ReplaceArrayValue 来强制替换以前的值而不是递归合并。

例如:

$array1 = [
    'name' => 'Yii',
    'version' => '1.1',
    'ids' => [
        1,
    ],
    'validDomains' => [
        'example.com',
        'www.example.com',
    ],
    'emails' => [
        'admin' => 'admin@example.com',
        'dev' => 'dev@example.com',
    ],
];

$array2 = [
    'version' => '2.0',
    'ids' => [
        2,
    ],
    'validDomains' => new \yii\helpers\ReplaceArrayValue([
        'yiiframework.com',
        'www.yiiframework.com',
    ]),
    'emails' => [
        'dev' => new \yii\helpers\UnsetArrayValue(),
    ],
];

$result = ArrayHelper::merge($array1, $array2);

结果为:

[
    'name' => 'Yii',
    'version' => '2.0',
    'ids' => [
        1,
        2,
    ],
    'validDomains' => [
        'yiiframework.com',
        'www.yiiframework.com',
    ],
    'emails' => [
        'admin' => 'admin@example.com',
    ],
]

ArrayHelper::getValue

使用标准 PHP,从一个数组、对象或由这两者组成的复杂结构中检索值是非常重复性的。你必须先用 isset 来检查它的 key 是否存在,如果存在,你会得到它,如果不存在,提供默认值,具体如下:

class User
{
    public $name = 'Alex';
}

$array = [
    'foo' => [
        'bar' => new User(),
    ]
];

$value = isset($array['foo']['bar']->name) ? $array['foo']['bar']->name : null;

Yii 提供了一个非常方便的方法:

$value = ArrayHelper::getValue($array, 'foo.bar.name');

第一个方法参数是我们从哪里获取值。第二个参数指定如何获取数据。可能是下面的一种:

  • 要从中检索值的数组键或对象属性的名称。
  • 以点分隔的数组键或对象属性名的集合。正是我们在上面的例子中使用的那个。
  • 返回值的回调函数

回调函数应该如下所示:

$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});

第三个可选参数是默认值 null,如果没有指定,可以使用如下方式:

$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');

ArrayHelper::setValue

从 Yii 2.0.13 版本开始,提供此方法,将值写入指定的键路径的关联数组。示例如下:

$array = [
    'key' => [
        'in' => ['k' => 'value']
    ]
];

ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);
// the path to write the value in `$array` can be specified as an array
ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);

结果,$array['key']['in'] 的初始值将被新值覆盖:

[
    'key' => [
        'in' => ['arr' => 'val']
    ]
]

如果路径包含一个不存在的键,它将被创建:

// if `$array['key']['in']['arr0']` is not empty, the value will be added to the array
ArrayHelper::setValue($array, 'key.in.arr0.arr1', 'val');

// if you want to completely override the value `$array['key']['in']['arr0']`
ArrayHelper::setValue($array, 'key.in.arr0', ['arr1' => 'val']);

结果为:

[
    'key' => [
        'in' => [
            'k' => 'value',
            'arr0' => ['arr1' => 'val']
        ]
    ]
]

ArrayHelper::remove

该方法可以从数组中移除项并返回该值。如果该键在数组中不存在,则返回默认值。如果你想要获取一个值,然后立即从数组中删除它,你可以使用 remove 方法:

$array = ['type' => 'A', 'options' => [1, 2]];
$type = ArrayHelper::remove($array, 'type');

执行代码的 $array 将包含 ['options' => [1, 2]]$type 将为 A。注意,与 getValue 方法不同,remove 只支持简单的键名。

ArrayHelper::removeValue

从 Yii 2.0.11 版本开始提供这个方法,从数组中移除值匹配的项并返回被移除的项。例如:

$array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
$removed = ArrayHelper::removeValue($array, 'Jackson');
// result:
// $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
// $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];

ArrayHelper::index

为了根据指定的键索引数组,可以使用 index 方法。输入应该是多维数组或对象数组。

第二个参数 $key 可以是子数组的键名,对象的属性名,或者一个必须返回值作为键的匿名函数。第三个参数 $groups 属性是一个键数组,用于根据指定的键将输入数组分组为一个或多个子数组。

如果 $key 属性或特定元素的值为 null$groups 未定义,则数组元素将被丢弃。相反,如果指定了 $groups,数组元素将被添加到结果数组中,而不需要任何键。

例如:

$array = [
    ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
    ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = ArrayHelper::index($array, 'id');

结果将是一个关联数组,其中键是 id 属性的值:

[
    '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
    // The second element of an original array is overwritten by the last element because of the same id
]

匿名函数,作为 $key 传递,给出相同的结果:

$result = ArrayHelper::index($array, function ($element) {
    return $element['id'];
});

传递 id 作为第三个参数将 $array 通过 id 分组:

$result = ArrayHelper::index($array, null, 'id');

按照 id 在第一级分组,而不是在第二级索引,结果将是一个多维数组:

[
    '123' => [
        ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
    ],
    '345' => [ // all elements with this index are present in the result array
        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
    ]
]

匿名函数也可以在分组数组中使用:

$result = ArrayHelper::index($array, 'data', [function ($element) {
    return $element['id'];
}, 'device']);

在第一级按 id 分组,在第二级按 device 分组,在第三级按 data 索引,结果将是一个多维数组:

[
    '123' => [
        'laptop' => [
            'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
        ]
    ],
    '345' => [
        'tablet' => [
            'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
        ],
        'smartphone' => [
            'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
        ]
    ]
]

ArrayHelper::getColumn

该方法,返回数组中指定列的值。通常您可能需要从数据行或对象数组中获取一列值。常见的例子是获取一个 id 列表。

$array = [
    ['id' => '123', 'data' => 'abc'],
    ['id' => '345', 'data' => 'def'],
];
$ids = ArrayHelper::getColumn($array, 'id');

结果为 ['123', '345']

如果需要额外的转换或者获取值的方式很复杂,第二个参数可以指定为匿名函数:

$result = ArrayHelper::getColumn($array, function ($element) {
    return $element['id'];
});

ArrayHelper::map

为了从多维数组或对象数组中构建一个 map(键值对),你可以使用 map 方法。$from$to 参数指定用于设置映射的键名或属性名。您也可以根据分组字段 $group 对映射进行分组。例如:

$array = [
    ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
    ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
    ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
];

$result = ArrayHelper::map($array, 'id', 'name');
// the result is:
// [
//     '123' => 'aaa',
//     '124' => 'bbb',
//     '345' => 'ccc',
// ]

$result = ArrayHelper::map($array, 'id', 'name', 'class');
// the result is:
// [
//     'x' => [
//         '123' => 'aaa',
//         '124' => 'bbb',
//     ],
//     'y' => [
//         '345' => 'ccc',
//     ],
// ]

ArrayHelper::keyExists

ArrayHelper::keyExists 的工作方式与 PHP 数组函数 array_key_exists() 类似,额外的,它还支持不区分大小写的键比较。例如:

$data1 = [
    'userName' => 'Alex',
];

$data2 = [
    'username' => 'Carsten',
];

if (!ArrayHelper::keyExists('username', $data1, false) || !ArrayHelper::keyExists('username', $data2, false)) {
    echo "Please provide username.";
}

ArrayHelper::multisort

multisort 方法,有助于我们按一个或几个键,对对象数组或嵌套数组进行排序。例如:

$data = [
    ['age' => 30, 'name' => 'Alexander'],
    ['age' => 30, 'name' => 'Brian'],
    ['age' => 19, 'name' => 'Barney'],
];
ArrayHelper::multisort($data, ['age', 'name'], [SORT_ASC, SORT_DESC]);

在排序之后,我们将在 $data 中得到以下内容:

[
    ['age' => 19, 'name' => 'Barney'],
    ['age' => 30, 'name' => 'Brian'],
    ['age' => 30, 'name' => 'Alexander'],
];

第二个参数,用来指定要排序的键,如果是一个单键,可以是一个字符串,如果是多个键,或者一个匿名函数,可以是一个数组,就像下面的一个:

ArrayHelper::multisort($data, function($item) {
    // sort by age if it exists or by name otherwise
    return isset($item['age']) ? $item['age'] : $item['name'];
});

第三个参数是排序方向。如果按单个键排序,它可以是 SORT_ASCSORT_DESC。如果按多个值排序,则可以通过提供排序方向数组对每个值进行不同的排序。

最后一个参数是 PHP 排序标志,它可以接受与传递给 PHP 函数 sort() 的值相同的值。

ArrayHelper::htmlEncode

该方法,将字符串数组中的特殊字符编码成HTML实体。具体如下:

$encoded = ArrayHelper::htmlEncode($data);

默认情况下,只对数组值进行编码。如果一个值是一个数组,这个方法也会递归地对它进行编码。只对字符串值进行编码。

通过传递第二个参数为 false,你也可以编码数组的键。编码将使用应用程序字符集,可以通过第三个参数进行更改。

ArrayHelper::htmlDecode

该方法,将 HTML 实体解码为字符串数组中相应的字符。具体如下:

$decoded = ArrayHelper::htmlDecode($data);

默认情况下,只有数组值将被解码。如果一个值是一个数组,这个方法也会递归地解码它。只有字符串值将被解码。

通过传递第二个参数为 false,你也可以编码数组的键。编码将使用应用程序字符集,可以通过第三个参数进行更改。

ArrayHelper::isAssociative

该方法,返回一个值,该值指示给定数组是否是关联数组。例如:

// all keys are strings
$associative = ['framework' => 'Yii', 'version' => '2.0'];
echo ArrayHelper::isAssociative($associative);

如果数组的所有键都是字符串,则数组是关联的。如果第二个参数 $allStrings 值是 false, 然后,如果数组中至少有一个键是字符串,则该数组将被视为关联数组。

注意: 空数组不会被认为是一个关联数组的。

ArrayHelper::isIndexed

该方法,返回一个值,该值指示给定数组是否是索引数组。例如:

// no keys specified
$indexed = ['Qiang', 'Paul'];
echo ArrayHelper::isIndexed($indexed);

如果数组的所有键都是整数,数组就会被索引。如果第二个参数 $consecutive 的值是 true,然后,数组键必须是从 0 开始的连续序列。

注意:空数组将被视为一个索引数组。

ArrayHelper::isIn

Yii 2.0.7 版本开始提供该方法,用来检查数组或 实现 Traversable 接口的对象,是否包含元素。例如:

// true
ArrayHelper::isIn('a', ['a']);

// true
ArrayHelper::isIn('a', new ArrayObject(['a']));

该方法与 PHP 函数 in_array() 作用类似,但是,额外还适用于实现 Traversable 接口的对象。

ArrayHelper::isTraversable

Yii 2.0.8 版本开始提供该方法,用来检查一个变量是数组还是 Traversable。例如:

// true
ArrayHelper::isTraversable(['a']);

// true
ArrayHelper::isTraversable(new ArrayObject(['a']));

该方法与 PHP 函数 is_array() 作用类似,但是,额外还适用于实现 Traversable 接口的对象。

ArrayHelper::isSubset

Yii 2.0.7 版本开始提供该方法,用来检查一个数组或 Traversable 是否是另一个数组或 Traversable 的子集。例如:

// true
ArrayHelper::isSubset(['a', 'c'], ['a', 'b', 'c']);

// true
ArrayHelper::isSubset(new ArrayObject(['a', 'c']), new ArrayObject(['a', 'b', 'c']));

如果首参 $needles 的所有元素都包含在第二个参数 $haystack 中,这个方法将返回 true。如果至少缺少一个元素,则返回 false

ArrayHelper::filter

Yii 2.0.9 版本开始提供该方法,用来根据指定的规则过滤数组。例如:

$array = [
    'A' => [1, 2],
    'B' => [
        'C' => 1,
        'D' => 2,
    ],
    'E' => 1,
];

$result = \yii\helpers\ArrayHelper::filter($array, ['A']);
// $result will be:
// [
//     'A' => [1, 2],
// ]

$result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
// $result will be:
// [
//     'A' => [1, 2],
//     'B' => ['C' => 1],
// ]

$result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
// $result will be:
// [
//     'B' => ['D' => 2],
// ]

第二个参数 $filters,定义数组键的规则,这些键应该从结果中保留或删除。每个规则是:

  • var$array['var'] 将留在结果中
  • var.key:只有 $array['var']['key'] 将留在结果中
  • !var.key$array['var']['key'] 将会从结果中移除

Console

控制台助手类,为与命令行相关的任务提供了有用的方法,比如,获取输入、格式化和彩色输出等。一般在继承了 yii\console\Controller 类的控制器中的动作方法中使用,例如:

namespace console\controllers;

use yii\console\Controller;
use yii\helpers\Console;

class TestController extends Controller
{
    public function actionIndex()
    {
        // Console:: ...

        // 输出
        $this->stdout($this->ansiFormat('Success', Console::FG_GREEN) . "\n", Console::ITALIC);
    }
}

Console::moveCursorUp

通过向终端发送 ANSI 控制代码 CUU,向上移动终端光标。如果光标已经在屏幕边缘,则没有效果。示例如下:

// $rows 光标应该向上移动的行数,默认为 1
Console::moveCursorUp($rows);

Console::moveCursorDown

通过向终端发送 ANSI 控制代码 CUD,向下移动终端光标。如果光标已经在屏幕边缘,则没有效果。示例如下:

// $rows 光标应该向下移动的行数,默认为 1
Console::moveCursorDown($rows);

Console::moveCursorForward

通过向终端发送 ANSI 控制代码 CUF,向前移动终端光标。如果光标已经在屏幕边缘,则没有效果。示例如下:

// $steps 光标向前移动的步数,默认为 1
Console::moveCursorForward($steps);

Console::moveCursorBackward

通过向终端发送 ANSI 控制代码 CUB,向后移动终端光标。如果光标已经在屏幕边缘,则没有效果。示例如下:

// $steps 光标向后移动的步数,默认为 1
Console::moveCursorBackward($steps);

Console::moveCursorNextLine

通过向终端发送 ANSI 控制代码 CNL,将终端光标移动到下一行的开头。示例如下:

// $lines 光标应该向下移动的行数,默认为 1
Console::moveCursorNextLine($lines);

Console::moveCursorPrevLine

通过向终端发送 ANSI 控制代码 CPL,将终端光标移动到上一行的开头。示例如下:

// $lines 光标应该向上移动的行数,默认为 1
Console::moveCursorPrevLine($lines);

Console::moveCursorTo

通过向终端发送 ANSI 控制代码 CUP 或 CHA,将光标移动到作为列和行给定的绝对位置。示例如下:

// $column 基于1的列号,1是屏幕的左边缘。
// $row 基于1的行号,1是屏幕的上边缘。如果没有设置,将只移动光标在当前行。
Console::moveCursorTo($column, $row);

Console::scrollUp

通过向终端发送 ANSI 控制代码 SU 来向上滚动整个页面。新行会添加在底部。在 windows 中使用 ANSI.SYS 是不支持的。例如:

// $lines 向上滚动的行数,默认为 1
Console::scrollUp($lines);

Console::scrollDown

通过向终端发送 ANSI 控制代码 SU 来向下滚动整个页面。新行会添加在顶部。在 windows 中使用 ANSI.SYS 是不支持的。例如:

// $lines 向下滚动的行数,默认为 1
Console::scrollDown($lines);

Console::saveCursorPosition

通过向终端发送 ANSI 控制代码 SCP 来保存当前光标位置。然后可以使用 restoreCursorPosition() 恢复位置。例如:

Console::saveCursorPosition();

Console::restoreCursorPosition

通过发送 ANSI 控制代码 RCP 到终端,恢复用 saveCursorPosition() 保存的光标位置。例如:

Console::restoreCursorPosition();

Console::hideCursor

通过向终端发送 ANSI DECTCEM 码 ?25l 来隐藏游标。使用 showCursor() 恢复显示。例如:

Console::hideCursor();

注意:不要忘记在应用程序退出时显示光标。退出后光标可能会隐藏在终端中。

Console::showCursor

hideCursor() 通过向终端发送 ANSI DECTCEM 码 ?25h 来隐藏光标时,将再次显示光标。例如:

Console::showCursor();

Console::clearScreen

通过向终端发送参数 2 的 ANSI 控制代码 ED 来清除整个屏幕内容。光标的位置不会被改变。例如:

Console::clearScreen();

注意:在 windows 中使用 ANSI.SYS 实现,将光标位置重置到屏幕的左上角。

Console::clearScreenBeforeCursor

通过向终端发送参数 1 的 ANSI 控制代码 ED,清除从光标到屏幕开头的文本。光标的位置不会被改变。例如:

Console::clearScreenBeforeCursor();

Console::clearScreenAfterCursor

通过向终端发送参数为 0 的 ANSI 控制代码 ED,清除从光标到屏幕末端的文本。光标的位置不会被改变。例如:

Console::clearScreenAfterCursor();

Console::clearLine

通过将参数 2 的 ANSI 控制代码 EL 发送给终端,清除当前光标所在的行。光标的位置不会被改变。例如:

Console::clearLine();

Console::clearLineBeforeCursor

通过向终端发送参数为 1 的 ANSI 控制代码 EL,清除从光标位置到行首的文本。光标的位置不会被改变。例如:

Console::clearLineBeforeCursor();

Console::clearLineAfterCursor

通过向终端发送参数为 0 的 ANSI 控制代码 EL,清除从光标位置到行尾的文本。光标的位置不会被改变。例如:

Console::clearLineAfterCursor();

Console::ansiFormatCode

根据给定的格式化常量,返回 ANSI 格式代码。例如:

// $format 包含格式化值的数组
// 你可以传递任何 `FG_*`,`BG_*` 等格式的常量
// 或者 [[xtermFgColor]] 和 [[xtermBgColor]] 指定格式。

$format = [Console::FG_RED, Console::BG_GREEN];
$ansi_code = Console::ansiFormatCode($format);

Console::beginAnsiFormat

输出 ANSI 格式代码,该代码会影响随后打印的任何文本的格式。例如:

Console::beginAnsiFormat([Console::FG_RED]);

Console::endAnsiFormat

重置之前 beginAnsiFormat() 方法设置的任何 ANSI 格式,在此之后的任何输出将具有默认的文本格式。例如:

Console::endAnsiFormat();
// 等价于
echo Console::ansiFormatCode([Console::RESET]);

Console::ansiFormat

将返回一个以给定 ANSI 样式格式化的字符串。例如:

$str_ansi = Console::ansiFormat('xxx', [Console::FG_RED, Console::BG_GREEN]);

Console::xtermFgColor

返回 xterm 前景色的 ANSI 格式代码。你可以将这个返回值传递给 ansiFormatansiFormatCodebeginAnsiFormat 等其中一个格式化方法。例如:

$code_ansi = Console::xtermFgColor($xterm_color_code);

Console::xtermBgColor

返回 xterm 背景颜色的 ANSI 格式代码。你可以将这个返回值传递给 ansiFormatansiFormatCodebeginAnsiFormat 等其中一个格式化方法。例如:

$code_ansi = Console::xtermBgColor($xterm_color_code);

Console::stripAnsiFormat

从字符串中剥离 ANSI 控制代码。例如:

$str = Console::stripAnsiFormat($str_has_ansi_control_code);

Console::ansiStrlen

返回不带 ANSI 颜色代码的字符串长度。例如:

$length = Console::ansiStrlen($str_has_ansi_corlor_code);

Console::ansiStrwidth

Yii 2.0.36 版本开始提供此方法,返回不带 ANSI 颜色代码的字符串的宽度。例如:

$width = Console::ansiStrwidth($str_has_ansi_corlor_code);

Console::ansiColorizedSubstr

返回由开始和长度参数指定的字符串的 ANSI 颜色代码部分。如果字符串有颜色代码,那么将返回 “TEXT_COLOR + TEXT_STRING + DEFAULT_COLOR”,否则将是简单的 “TEXT_STRING”。例如:

$str_ansi_color = Console::ansiColorizedSubstr($str, 0, 8);

Console::ansiToHtml

将 ANSI 格式的字符串转换为 HTML。例如:

// $styleMap 一个可选的 ANSI 控制代码的映射,例如,FG\_*COLOR* 或 [[BOLD]] 指向一组 css 样式定义,CSS 样式定义表示为一个数组,数组键对应于 CSS 样式属性名,值是 CSS 值。值可以是数组,在呈现时使用 `' '` 进行合并和内爆。

$styleMap = [
    Console::FG_RED => [
        'color' => 'red',
    ],
];
$html = Console::ansiToHtml($str_ansi, $styleMap);

注意:xTerm 256 位颜色目前不支持。

Console::markdownToAnsi

通过应用一些 ANSI 格式将 Markdown 转换为在控制台环境中更好的可读性。

$str = Console::ansiToHtml($str_markdown);

Console::renderColoredString

将字符串转换为 ANSI 格式,方法是用 ANSI 控制代码替换像 %y(表示黄色)这样的模式。与 github.com/pear/Console_Color2/blo... 使用几乎相同的语法。例如:

// $str 参数是要转换的字符串
// $colored 标志是否使用颜色,默认为 true,如果设置为 false,颜色代码将被删除(%% 将被转换为 %)
$str_ansi = Console::renderColoredString($str, $colored);

转换表是:(在某些终端上 ‘粗体’ 表示 ‘轻’)。它几乎与 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 %

Console::escape

转义 %,所以,当 renderColoredString 解析字符串时,它们不会被解释为颜色代码。例如:

$str_escape = Console::escape($str);

Console::streamSupportsAnsiColors

如果 stream 支持着色,则返回 true,如果 stream 不支持 ANSI 颜色,那么它不可用。例如:

$is_support = Console::streamSupportsAnsiColors($stream);

Console::isRunningOnWindows

如果控制台在 windows 上运行,则返回 true,反之 false。例如:

$is_windows = Console::streamSupportsAnsiColors();

Console::getScreenSize

返回终端屏幕尺寸。当它不能确定大小的时候,会返回 false。例如:

// $refresh 是否强制检查和不重用缓存大小值,默认为 false
list($width, $height) = ConsoleHelper::getScreenSize($refresh);

注意:这个方法对于在应用程序运行时,检测窗口大小的变化非常有用,但可能无法在每个终端上获得最新的值。

Console::wrapText

Yii 2.0.4 版本开始提供该方法,返回带缩进以适应屏幕大小的换行文本。如果不能检测到屏幕大小,或者缩进大于屏幕大小,文本将不会被换行。第一行将 缩进。例如:

// $indent 用于缩进的空格数,默认为 0
// $refresh 是否强制刷新屏幕大小,默认为 false
$text = 'Lorem ipsum dolor sit amet.';
$indent = 4;
$text_wrapped = Console::wrapText($text, $indent, $refresh);

// 假设指定屏幕宽度为 16 个字符,结果是:
Lorem ipsum
    dolor sit
    amet.

Console::stdin

从 STDIN 获取输入,并返回针对换行符 EOL 进行从右边裁剪(PHP 函数 rtrim())的字符串。例如:

// $raw 如果设置为true,则返回原始字符串而不进行修剪,默认为 false
$str = Console::stdin($raw);

Console::stdout

打印一个字符串到 STDOUT,成功时返回打印的字节数,错误时为 false,例如:

$num_bytes = Console::stdout($str);

Console::stderr

打印一个字符串到 STDERR,成功时返回打印的字节数,错误时为 false,例如:

$num_bytes = Console::stderr($str);

Console::input

请求用户输入,当用户输入回车(PHP_EOL)时结束。它还可以提供一个提示符。例如:

// $prompt 等待输入之前要显示的提示符,默认是 null
$str = Console::input($prompt);

Console::output

将文本打印到 STDOUT,并附加回车符(PHP_EOL)。成功时返回打印的字节数,错误时为 false,例如:

$num_bytes = Console::output($str);

Console::error

打印文本到 STDERR,并附加一个回车符(PHP_EOL)。成功时返回打印的字节数,错误时为 false,例如:

$num_bytes = Console::error($str);

Console::prompt

对用户的输入,提示并对其进行验证,通过验证后返回用户的输入字符串。以下是支持的验证输入的选项:

  • required: 是否是必填项
  • default: 用户没有输入时的默认值
  • pattern: 验证输入的正则表达式模式
  • validator: 验证输入的回调函数,该函数必须接受两个参数:
    • input: 要验证的用户输入内容
    • error: 验证失败时通过引用传递的错误值。

示例代码如下:

// $options 验证输入的选项,默认为 []
$options = [
    'required' => true,
    //'default' => 'yes',
    //'pattern' => '/^[a-zA-Z0-9_]+$/',
    /*'validator' => function($input, $error){
        // ...
        // return ture;
    },*/
];
$str = Console::prompt($text, $options);

Console::confirm

询问用户输入 y 或 n 进行确认。典型的用法,如下所示:

// $default 如果没有进行选择,则返回该值,默认为 false
if (Console::confirm("Are you sure?", $default)) {
    echo "user typed yes\n";
} else {
    echo "user typed no\n";
}

Console::select

给用户一个可供选择的选项。当输入 ‘?’ 时,就会显示出可供选择的选项及其解释。

// $prompt 提示消息
// $options 要选择的选项的 键-值 数组。
// 键是输入和使用的内容,值是通过帮助命令显示给终端用户的内容。
$options = [
    'exit' => 'exit cmd',
];
$str = Console::select($prompt, $options);

Console::startProgress

开始在屏幕上显示进度条。这个进度条将由 updateProgress() 更新,并可能由 endProgress() 结束。下面的例子展示了进度条的简单用法:

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

Git clone like progress (只显示状态信息):

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

Console::updateProgress

更新由 startProgress() 启动的进度条。

Console::endProgress

结束由 startProgress() 启动的进度条。

Console::errorSummary

Yii 2.0.14 版本开始,提供此方法,用于生成验证错误的摘要,并返回该字符串。

// $models 要显示其验证错误的模型
// $options 以 名称-值 对表示的标记选项。以下选项是特殊处理的:
// showAllErrors:如果设置为 true,将显示每个属性的每个错误消息,否则只显示每个属性的第一个错误消息。默认为 `false`。
$str = Console::errorSummary($models, $options);

FileHelper

文件系统助手类。

FileHelper::$mimeMagicFile

包含 MIME 类型信息的 PHP 文件的路径(或别名)。

FileHelper::$mimeAliasesFile

Yii 2.0.14 版本开始提供此属性,包含 MIME 别名的 PHP 文件的路径(或别名)。

FileHelper::normalizePath

规范化 文件/目录 的路径。标准化做了以下工作:

  • 将所有目录分隔符转换为 DIRECTORY_SEPARATOR (如 “\a/b\c” 变成 “/a/b/c”)
  • 删除尾随目录分隔符 (如 “/a/b/c/“ 变成 “/a/b/c”)
  • 将多个连续斜杠变成一个单独的斜杠 (如 “/a///b/c” 变成 “/a/b/c”)
  • 基于 “..” 和 “.” 的含义,删除它们 (如 “/a/./b/../c” 变成 “/a/c”)

代码示例如下:

$path_normalize = FileHelper::normalizePath($path);

注意:对于已注册的 stream 包装器,将跳过连续的斜杠规则和 “..” / “.” 的转换。

FileHelper::localize

返回指定文件的本地化版本。

这个搜索查询基于指定的语言编码。特别是,将在名称与语言代码相同的子目录下查找具有相同名称的文件。例如,给定文件 “path/to/view.php” 和 语言编码 “zh-CN”,那么,本地化文件将被作为 “path/to/zh-CN/view.php” 查找。如果没有找到该文件,它将尝试使用 “zh” 语言代码作为备选方案,如 “path/to/zh/view.php”。如果没有找到,则返回原始文件。

如果目标和源语言代码相同,则返回原始文件。

// $language 本地化目标语言。缺省时调用 `yii\base\Application::language` 的值
// $sourceLanguage 文件的源语言。缺省时调用,`yii\base\Application::language` 的值
$file_localized = FileHelper::localize($file, $language, $sourceLanguage);

FileHelper::getMimeType

确定指定文件的 MIME 类型。这个方法将首先尝试基于 PHP 函数 finfo_open 确定 MIME 类型。如果没有安装 PHP fileinfo 扩展,当第三个参数 $checkExtension 为 true 时,会调用 getMimeTypeByExtension() 方法。

// $magicFile magic 数据库文件的名称(或别名),通常类似于  `/path/to/magic.mime`,默认为 null
// 当安装了 `fileinfo` 扩展,这将作为第二个参数传递给 `finfo_open()`。如果 MIME 类型是通过 `getMimeTypeByExtension()` 确定的,并且这是 null,它将使用由 `mimeMagicFile` 指定的文件。
$mine_type = FileHelper::getMimeType($file, $magicFile, $checkExtension);

FileHelper::getMimeTypeByExtension

根据指定文件的扩展名确定 MIME 类型。此方法将使用扩展名和 MIME 类型之间的本地映射。

// $magicFile 包含所有可用 MIME 类型信息的文件的路径(或别名)。如果缺省,将使用`$mimeMagicFile` 指定的文件。
$mine_type = FileHelper::getMimeTypeByExtension($file, $magicFile);

FileHelper::getExtensionsByMimeType

根据给定的 MIME 类型确定并返回扩展名数组。此方法将使用扩展名和 MIME 类型之间的本地映射。

// $magicFile 包含所有可用 MIME 类型信息的文件的路径(或别名)。如果缺省,将使用`$mimeMagicFile` 指定的文件。
$mimeType = 'image/jpeg';
$mine_type = FileHelper::getExtensionsByMimeType($mimeType, $magicFile);

FileHelper::copyDirectory

将一个完整文件目录拷贝到另一个目录。文件和子目录也将被拷贝。

options for directory copy. Valid options are:

  • dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.

  • fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.

  • filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path), where $path refers the full path to be filtered. The callback can return one of the following values:

    • true: the directory or file will be copied (the “only” and “except” options will be ignored)
    • false: the directory or file will NOT be copied (the “only” and “except” options will be ignored)
    • null: the “only” and “except” options will determine whether the directory or file should be copied
  • only: array, list of patterns that the file paths should match if they want to be copied.
    A path matches a pattern if it contains the pattern string at its end.
    For example, ‘.php’ matches all file paths ending with ‘.php’.
    Note, the ‘/‘ characters in a pattern matches both ‘/‘ and ‘' in the paths.
    If a file path matches a pattern in both “only” and “except”, it will NOT be copied.

  • except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
    A path matches a pattern if it contains the pattern string at its end.
    Patterns ending with ‘/‘ apply to directory paths only, and patterns not ending with ‘/‘
    apply to file paths only. For example, ‘/a/b’ matches all file paths ending with ‘/a/b’;
    and ‘.svn/‘ matches directory paths ending with ‘.svn’. Note, the ‘/‘ characters in a pattern matches
    both ‘/‘ and ‘' in the paths.

  • caseSensitive: boolean, whether patterns specified at “only” or “except” should be case sensitive. Defaults to true.

  • recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.

  • beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
    If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
    The signature of the callback should be: function ($from, $to), where $from is the sub-directory or
    file to be copied from, while $to is the copy target.

  • afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
    The signature of the callback should be: function ($from, $to), where $from is the sub-directory or
    file copied from, while $to is the copy target.

  • copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories
    that do not contain files. This affects directories that do not contain files initially as well as directories that
    do not contain files at the target destination because files have been filtered via only or except.
    Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.

FileHelper::copyDirectory($src, $dst, $options);

FileHelper::removeDirectory

Removes a directory (and all its content) recursively.
$options options for directory remove. Valid options are:

  • traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
    Defaults to false, meaning the content of the symlinked directory would not be deleted.
    Only symlink would be removed in that default case.
FileHelper::removeDirectory($dir, $options);

FileHelper::unlink

Yii 2.0.14 版本开始提供此方法,以跨平台的方式删除文件或符号链接,并返回布尔类型的结果。

$res = FileHelper::unlink($path);

FileHelper::findFiles

Returns the files found under the specified directory and subdirectories. files found under the directory, in no particular order. Ordering depends on the files system used. 第二个参数 $options 是文件搜索选项。Valid options are:

  • filter: callback, a PHP callback that is called for each directory or file.
    The signature of the callback should be: function ($path), where $path refers the full path to be filtered.
    The callback can return one of the following values:
    • true: the directory or file will be returned (the only and except options will be ignored)
    • false: the directory or file will NOT be returned (the only and except options will be ignored)
    • null: the only and except options will determine whether the directory or file should be returned
  • except: array, list of patterns excluding from the results matching file or directory paths.
    Patterns ending with slash (‘/‘) apply to directory paths only, and patterns not ending with ‘/‘
    apply to file paths only. For example, ‘/a/b’ matches all file paths ending with ‘/a/b’;
    and .svn/ matches directory paths ending with .svn.
    If the pattern does not contain a slash (/), it is treated as a shell glob pattern
    and checked for a match against the pathname relative to $dir.
    Otherwise, the pattern is treated as a shell glob suitable for consumption by fnmatch(3)
    with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname.
    For example, views/*.php matches views/index.php but not views/controller/index.php.
    A leading slash matches the beginning of the pathname. For example, /*.php matches index.php but not views/start/index.php.
    An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again.
    If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (\) in front of the first !
    for patterns that begin with a literal !, for example, \!important!.txt.
    Note, the ‘/‘ characters in a pattern matches both ‘/‘ and ‘' in the paths.
  • only: array, list of patterns that the file paths should match if they are to be returned. Directory paths
    are not checked against them. Same pattern matching rules as in the except option are used.
    If a file path matches a pattern in both only and except, it will NOT be returned.
  • caseSensitive: boolean, whether patterns specified at only or except should be case sensitive. Defaults to true.
  • recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
$file_arr = FileHelper::findFiles($dir, $options);

FileHelper::findDirectories

Yii 2.0.14 版本开始提供此方法,Returns the directories found under the specified directory and subdirectories. directories found under the directory, in no particular order. Ordering depends on the files system used. 第二个参数 $options 是目录搜索选项. Valid options are:

  • filter: callback, a PHP callback that is called for each directory or file.
    The signature of the callback should be: function (string $path): bool, where $path refers the full path to be filtered. The callback can return one of the following values:
    • true: the directory will be returned
    • false: the directory will NOT be returned
  • recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.

See [[findFiles()]] for more options.

$file_arr = FileHelper::findDirectories($dir, $options);

FileHelper::filterPath

检查给定的文件路径是否满足过滤选项。第二个参数 $options 是目录搜索选项,See [[findFiles()]] for explanations of the supported options.

$res = FileHelper::filterPath($path, $options);

FileHelper::createDirectory

创建一个新目录,成功返回 true。
This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.

$res = FileHelper::createDirectory($path, $mode, $recursive);

FileHelper::changeOwnership

Yii 2.0.43 版本开始提供此方法,Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
第二个参数 $ownership 是 the user and/or group ownership for the file or directory. When $ownership is a string, the format is ‘user:group’ where both are optional. E.g. ‘user’ or ‘user:’ will only change the user, ‘:group’ will only change the group, ‘user:group’ will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. [$myUser, $myGroup]. It is also possible to pass an associative array, e.g. [‘user’ => $myUser, ‘group’ => $myGroup]. In case $owners is an integer it will be used as user id. If null, an empty array or an empty string is passed, the ownership will not be changed.

第三个参数 $mode 是 the permission to be set for the file or directory. If null is passed, the mode will not be changed.

FileHelper::changeOwnership($path, $ownership, $mode);

Note: This function will not work on remote files as the file to be examined must be accessible via the server’s filesystem.
Note: On Windows, this function fails silently when applied on a regular file.

FormatConverter

FormatConverter provides functionality to convert between different formatting pattern formats. It provides functions to convert date format patterns between different conventions.

FormatConverter::$phpFallbackDatePatterns

the php fallback definition to use for the ICU short patterns short, medium, long and full. This is used as fallback when the intl extension is not installed.

FormatConverter::$juiFallbackDatePatterns

the jQuery UI fallback definition to use for the ICU short patterns short, medium, long and full. This is used as fallback when the intl extension is not installed.

FormatConverter::convertDateIcuToPhp

Converts a date format pattern from [ICU format][] to php date() function format.
The conversion is limited to date patterns that do not use escaped characters.
Patterns like d 'of' MMMM yyyy which will result in a date like 1 of December 2014 may not be converted correctly because of the use of escaped characters.
Pattern constructs that are not supported by the PHP format will be removed.
php date() function format: www.php.net/manual/en/function.dat...
[ICU format]: userguide.icu-project.org/formatpar...

// $pattern date format pattern in ICU format.
// $type 'date', 'time', or 'datetime'.
// $locale the locale to use for converting ICU short patterns `short`, `medium`, `long` and `full`. If not given, `Yii::$app->language` will be used.
$pattern_format = FormatConverter::convertDateIcuToPhp($pattern, $type, $locale);

FormatConverter::convertDatePhpToIcu

Converts a date format pattern from php date() function format to [ICU format][].
Pattern constructs that are not supported by the ICU format will be removed.
php date() function format: www.php.net/manual/en/function.dat...
[ICU format]: userguide.icu-project.org/formatpar...
Since 2.0.13 it handles escaped characters correctly.

// $pattern date format pattern in php date()-function format.
$pattern_format = FormatConverter::convertDatePhpToIcu($pattern);

FormatConverter::convertDateIcuToJui

Converts a date format pattern from [ICU format][] to jQuery UI date format.

Pattern constructs that are not supported by the jQuery UI format will be removed.
jQuery UI date format: api.jqueryui.com/datepicker/#utilit...
[ICU format]: userguide.icu-project.org/formatpar...

// $pattern date format pattern in ICU format.
// $type 'date', 'time', or 'datetime'.
// $locale the locale to use for converting ICU short patterns `short`, `medium`, `long` and `full`. If not given, `Yii::$app->language` will be used.
$pattern_format = FormatConverter::convertDateIcuToJui($pattern, $type, $locale);

FormatConverter::convertDatePhpToJui

Converts a date format pattern from php date() function format to jQuery UI date format.
The conversion is limited to date patterns that do not use escaped characters.
Patterns like jS \o\f F Y which will result in a date like 1st of December 2014 may not be converted correctly because of the use of escaped characters.

Pattern constructs that are not supported by the jQuery UI format will be removed.

// $pattern date format pattern in php date()-function format.
$pattern_format = FormatConverter::convertDatePhpToJui($pattern);

Html

Html provides a set of static methods for generating commonly used HTML tags.

Nearly all of the methods in this class allow setting additional html attributes for the html tags they generate. You can specify, for example, class, style or id for an html element using the $options parameter. See the documentation of the [[tag()]] method for more details.

For more details and usage information on Html, see the guide article on html helpers.

HtmlPurifier

HtmlPurifier provides an ability to clean up HTML from any harmful code.

Basic usage is the following:

echo HtmlPurifier::process($html);

If you want to configure it:

echo HtmlPurifier::process($html, [
    'Attr.EnableID' => true,
]);

For more details please refer to HTMLPurifier documentation.

Image

Image implements most commonly used image manipulation functions using the Imagine library.

Example of use:

// generate a thumbnail image
Image::thumbnail('@webroot/img/test-image.jpg', 120, 120)
    ->save(Yii::getAlias('@runtime/thumb-test-image.jpg'), ['quality' => 50]);

Inflector

IpHelper

Json

Markdown

StringHelper

Url

VarDumper

自定义助手类

如果您想要自定义一个核心助手类(如 yii\helpers\ArrayHelper),你应该从对应的基类(如 yii\helpers\BaseArrayHelper)中创建一个新的类,将您的类命名为与相应的具体类相同的名称(如 yii\helpers\ArrayHelper),并包括其名称空间。然后这个类将被设置来替换框架的原始实现。

下面的列子展示了,如何自定义 yii\helpers\ArrayHelper::merge() 方法:


namespace yii\helpers;

class ArrayHelper extends BaseArrayHelper
{
    public static function merge($a, $b)
    {
        // your custom implementation
    }
}

将您的类保存到名为 ArrayHelper.php 的文件中,该文件可以在任何目录下,例如:@app/components

下一步,在你的应用入口文件中,在包含 yii.php 文件之后,添加以下代码行,告诉 Yii 类自动加载器 加载您的自定义类,而不是来自框架的原始助手类:

Yii::$classMap['yii\helpers\ArrayHelper'] = '@app/components/ArrayHelper.php';

注意:只有当你想改变助手类的一个现有函数的行为时,自定义助手类才有用。如果您想在您的应用程序中添加额外的功能,您最好为它创建一个单独的助手。

💖喜欢本文档的,欢迎点赞、收藏、留言或转发,谢谢支持!
作者邮箱:zhuzixian520@126.com,github地址:github.com/zhuzixian520

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
zhuzixian520
讨论数量: 0
发起讨论 只看当前版本


暂无话题~