m36/stringformatter

简单但强大的字符串格式化

此包的官方仓库似乎已丢失,因此该包已被冻结。

0.6.0 2016-05-22 09:39 UTC

This package is not auto-updated.

Last update: 2021-06-11 07:14:04 UTC


README

StringFormatter - 简单但强大的字符串格式化。

当前稳定版本

0.6.0

PHP版本

StringFormatter 支持 PHP 5.3+, 5.4+, 5.5+, 5.6+, 7.0+, 7.1+

使用方法

StringFormatter 由几个类组成,您只需手动使用其中的两个。这两个类都需要使用 format 方法来 编译 最终字符串,并使用一些 params(可选)来填充 format 中的占位符。占位符由花括号包围,包含索引(FormatterIndex 类)或名称(FormatterNamed 类),以及可选的修饰符。

最简单的使用方式可以是

$f = new FormatterIndex('{0} {1}!');
echo $f->compile('Hello', 'world')->eol(); # Hello world!

在这里,我们使用了 FormatterIndex 类,所以我们将使用索引占位符。定义了两个占位符:01。在某些情况下,我们可以省略索引

$f = new FormatterIndex('{} {}!');
echo $f->compile('Hello', 'world')->eol(); # Hello world!

这两段代码的结果是完全相同的。

当然,我们可以改变使用参数的顺序

$f = new FormatterIndex('{1} {0}!');
echo $f->compile('Hello', 'world')->eol(); # world Hello!

我们也可以在构造函数中传递占位符的参数

$f = new FormatterIndex('{} {}!', 'Hello', 'world');
echo $f->compile()->eol(); # Hello world!

还有 FormatterNamed 类,当我们不想使用索引来选择占位符的对象时

$f = new FormatterNamed('{hello} {name}!');
echo $f->compile(['name' => 'world', 'hello' => 'Hello']); # Hello world!

在这里,类似于 FormatterIndex 类,我们也可以在构造函数中传递参数。默认情况下,两个数组都会合并成一个,并用于占位符

$f = new FormatterNamed('{hello}, {name}!', ['hello' => 'Hi']);
echo $f->compile(['name' => 'Thomas'])->eol(); # Hi, Thomas!
echo $f->compile(['name' => 'Martha'])->eol(); # Hi, Martha!
echo $f->compile(['hello' => 'Welcome', 'name' => 'Bruce'])->eol(); # Welcome, Bruce!

通过 IFormatter::compile 方法的调用结果,我们得到了一个 Transformer 类的实例,它有一些额外的可能性(下面描述)。

内部结构

整个包主要关注两个方面

  • 使用模板(format)创建字符串,并用数据(params)替换占位符。这个过程称为 编译
  • 在编译后(转换)操作最终字符串

编译

通过调用方法 Compiler::run 来进行编译。通常,这是在您调用 IFormat::compileiformatiformatlnformat 时在幕后完成的。这个过程通常在您第一次评估 Tranformer 时完成(延迟评估),然后缓存,因此不再进行处理。

转换

Transformer 是您在调用 IFormatter::compileiformatiformatlnformat 函数在幕后调用它)后收到的对象。 Transformer 允许您在编译后创建的最终字符串上进行操作。

Transformer 的结果是不可变的。这意味着您可以存储一次转换的结果,添加新的转换,这不会修改先前的结果

 $adj = 'glorious';
 $char = '!';
 $normal = iformat('Some {} method{}', [$adj, $char]);
 $lower = $normal->lower()->eol();
 $surrounded = $normal->surround('@@@')->eol();
 echo $normal->eol(); # Some glorious method!
 echo $lower; # some glorious method!
 echo $surrounded; # @@@Some glorious method!@@@

$surrounded:它不像 $lower 那样转换为小写。

变压器在第一次调用Transformer::unfold方法(显式或隐式通过转换为字符串)时进行懒加载。此外,评估结果将被缓存,因此下次使用相同的Transformer将更加高效。

快捷键

嘿,还有更多哦;)

这两个类也提供了功能API。您不必手动创建对象、调用方法等,可以使用函数

$adj = 'glorious';
$char = '!';
echo iformat('Some {} method{}', [$adj, $char])->eol(); 
echo iformatl('Some {} method{}', $adj, $char)->eol(); 
echo nformat('Some {adj} method{char}', ['adj' => $adj, 'char' => $char])->eol(); 

iformatiformatl仅参数格式不同(数组或列表)。

对于PHP 5.6.0或更高版本,您可以仅导入这些函数

use function m36\StringFormatter\iformat;
use function m36\StringFormatter\iformatl;
use function m36\StringFormatter\nformat;

并且可以使用它们:)

格式化程序

文本对齐 - 左对齐

$f = new FormatterIndex('{} "{1:<20}"');
echo $f->compile('Hello', 'world')->eol(); # Hello "world               "

文本对齐 - 右对齐

$f = new FormatterIndex('{} "{1:>20}"');
echo $f->compile('Hello', 'world')->eol(); # Hello "               world"

文本对齐 - 居中对齐

$f = new FormatterIndex('{} "{1:^20}"');
echo $f->compile('Hello', 'world')->eol(); # Hello "       world        "

使用指定字符的对齐文本

$f = new FormatterIndex('{} "{1:*^20}"');
echo $f->compile('Hello', 'world')->eol(); # Hello "*******world********"

类似于sprintf的格式化(处理所有sprintf()能处理的占位符)

$f = new FormatterIndex('Test: {%%.3f}');
echo $f->compile(2.1234567)->eol(); # Test: 2.123
$f = new FormatterIndex('Test 2: {%%c}');
echo $f->compile(97)->eol(); # Test2: a

调用对象方法或获取对象属性

$f = new FormatterIndex('Test: {0->method} {->property}');
class TestStringFormatter {
    public $property = 'test property';
    public function method() {
        return 'test method';
    }
}
echo $f->compile(new TestStringFormatter(), new TestStringFormatter())->eol(); # Test: test method test property

将整数转换为其他基数

$f = new FormatterIndex('Test: 10: {#d}, 16: {0#x}, 2: {0#b}');
echo $f->compile(11)->eol(); # Test: 10: 11, 16: b, 2: 1011
$f = new FormatterIndex('Test: 10: {#10}, 16: {0#16}, 2: {0#2}, 7: {0#7}');
echo $f->compile(11)->eol(); # Test: 10: 11, 16: b, 2: 1011, 7: 14

可用的基数

  • b - 二进制
  • o - 八进制
  • d - 十进制
  • x - 十六进制(小写字母)
  • X - 十六进制(大写字母)

数组索引

$f = new FormatterIndex('Test: test1: {[test1]}, test2: {0[test2]}');
echo $f->compile(array('test1' => 'Hello', 'test2' => 'world'))->eol(); # Test: test1: Hello, test2: world

关键字

作为占位符,您可以使用以下关键字之一(不接受修饰符)

  • @class - 替换为当前类名(不带命名空间)。如果不在类中使用,将触发E_USER_WARNING。
  • @classLong - 替换为当前类名(带命名空间)。如果不在类中使用,将触发E_USER_WARNING。
  • @method - 替换为当前类名(不带命名空间)和类方法名。如果不在类中使用,将触发E_USER_WARNING。
  • @methodLong - 替换为当前类名(带命名空间)和类方法名。如果不在类中使用,将触发E_USER_WARNING。
  • @function - 替换为当前函数/方法名(不带命名空间和类名)。如果不在函数中使用,将触发E_USER_WARNING。
  • @file - 调用IFormatter::compile的文件名(不带父级)
  • @fileLong - 调用IFormatter::compile的文件的完整路径(带父级)
  • @dir - 调用IFormatter::compile的文件的目录名(不带父级)
  • @dirLong - 调用IFormatter::compile的文件的目录名(带父级)
  • @line - 调用IFormatter::compile的文件的行号(不带父级)

变压器列表

作为IFormatter::compile的返回值,我们得到了一个Transformer类的实例。为解析的字符串定义了一些简单且有用的变压器

  • replace - str_replace的包装器
  • ireplace - ireplace的包装器
  • regexReplace - preg_replacepreg_replace_callback的包装器(取决于$replacement是否为.callback)
  • strip - trim的包装器
  • lstrip - ltrim的包装器
  • rstrip - rtrim的包装器
  • upper - strtoupper的包装器
  • lower - strtolower的包装器
  • upperFirst - ucfirst的包装器
  • lowerFirst - lcfirst的包装器
  • upperWords - ucwords的包装器
  • wordWrap - wordwrap的包装器
  • substr - substr的包装器
  • eol - 在字符串末尾追加PHP_EOL
  • eoln - 在字符串末尾追加\n
  • eolrn - 在字符串末尾追加\r\n
  • suffix - 将指定的字符串追加到当前值的末尾
  • prefix - 将指定的字符串预置于当前值的开头
  • surround - 使用指定的字符串包围当前值

一些示例

// assume it's result of $request->query->all() from Symfony
$data = ['customerId' => 2, 'customerName' => 'John', 'customerLastName' => 'Wayne', 'age' => 24];
echo nformat('[{@file}:{@line}] Incoming data for customerId #{customerId}: first name: {customerName}, ' .
    'last name: {customerLastName}, age: {age}', $data)->eol();
# [example.php:12] Incoming data for customerId #2: first name: John, last name: Wayne, age: 24

// fetch data about package from Doctrine
$package = $this->em->find(Package::class, $request->get('packageId'));
$logger->info(nformat('[{@method}] Package id {packageId} found with data: {package->getName}, {package->getTechnology} created at {package->getCreateDate}', ['packageId' => $request->get('packageId'), 'package' => $package]));
# [Example::test] Package id 4 found with data: m36/StringFormatter, php created at 2016-05-19 12:02:16

$f = new FormatterNamed('{hello}, {name}!', ['hello' => 'Hi']);
$data = $f->compile(['name' => 'Thomas']);
echo $data->eol(); # Hi, Thomas!
echo $data->upper()->eol(); # HI, THOMAS!
echo $data->lower()->eol(); # hi, thomas!
echo $data->replace('!', '?')->eol(); # Hi, Thomas?
echo $data->replace(['!', ','], ['?', '@'])->eol(); # Hi@ Thomas?

安装

使用composer

composer require m36/stringformatter 

哇哦!

作者

Marcin Sztolcman m.sztolcman@36monkeys.com

联系方式

如果您喜欢或不喜欢这个软件,请随时通过电子邮件(m.sztolcman@36monkeys.com)告诉我。

如果您发现bug或对改进这个工具有任何想法,请使用GitHub的问题

许可证

MIT许可证(MIT)

版权所有(c)2016 Marcin Sztolcman

特此授予任何获得本软件及其相关文档文件(以下简称“软件”)副本的任何人免费使用软件的权利,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本,并允许软件的受让人按以下条件进行上述活动:

上述版权声明和许可声明应包含在软件的所有副本或主要部分中。

软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定目的和无侵权性的保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任承担责任,无论该责任是因合同、侵权或其他原因产生的,与软件或其使用或任何其他方式有关。

变更日志

(开发版)

  • 编译器可以返回评估参数的信息
  • m36\StringFormatter现在是惰性评估的
  • 添加了新的转换器:surround
  • 对于转换器Transformer::replaceTransformer::ireplace,第二个参数($to)可以是可调用函数(类似于Transformer::regexpReplace
  • 如果标记未知,则触发E_USER_WARNING
  • 为旧版PHP版本进行了许多改进
  • 添加了新的测试
  • 改进了代码文档
  • 内部优化和清理

v0.6.0

  • 许多转换器如果可用,将使用多字节字符串模块
  • 添加了新的转换器:Transformer::regexReplaceTransformer::repeatTransformer::reverseTransformer::squashWhitecharsTransformer::insertTransformer::ensurePrefixTransformer::ensureSuffix

v0.5.4

  • 缺少变更日志

v0.5.3

  • 修复了处理某些关键字在类或函数外部使用的问题

v0.5.2

  • 修复了composer.json版本问题

v0.5.1

  • 在功能API中使用@keywords在某些关键字上出现故障

v0.5.0

  • 第一个公开版本