hylianshield / alphabet
支持在指定字母表上操作库
1.0.0
2017-01-01 12:39 UTC
Requires
- php: ^7.0
- ext-spl: ^7.0
Requires (Dev)
- phpunit/phpunit: ^5.7.5
This package is auto-updated.
Last update: 2024-08-29 03:58:12 UTC
README
字母表库是标准化遍历给定字母表的手段。对于处理编码、密码学或文本处理的代码来说非常有用。
安装
composer require hylianshield/alphabet:^1.0
用法
字母表构造函数接受0(零)个或多个参数,参数类型为字符串。
字母表可以作为迭代器使用,并提供条目数。
<?php use \HylianShield\Alphabet\Alphabet; $alphabet = new Alphabet('A', 'B', 'C'); echo sprintf( 'Found %d entries:', count($alphabet) ) . PHP_EOL; foreach ($alphabet as $character) { echo $character . PHP_EOL; }
输出
Found 3 entries:
A
B
C
字母表解包
如果字母表的输入存在于PHP数组中,可以使用参数解包来填充字母表
<?php use \HylianShield\Alphabet\Alphabet; $input = range('A', 'Z'); $alphabet = new Alphabet(...$input); echo sprintf( 'Alphabet consists of %d characters.', count($alphabet) );
输出
Alphabet consists of 26 characters.
字母表(去)归一化
将字母表转换回扁平结构时,可以使用内置的PHP函数,iterator_to_array。
<?php use \HylianShield\Alphabet\Alphabet; /** * @var Alphabet $alphabet * @var string[] $normalized */ $normalized = iterator_to_array($alphabet, false); // And to de-normalize the alphabet again, simply unpack the array. $alphabet = new Alphabet(...$normalized);
将iterator_to_array
的第二个参数设置为false
,因为不需要解释和/或转换键。这是一个小的性能优化。
测试
要运行单元测试,检查代码,只需运行预配置的composer脚本之一
composer test
运行PHPUnitcomposer coverage
运行带文本覆盖的PHPUnitcomposer coverage-html
运行带HTML覆盖的PHPUnit并在浏览器中打开结果。