fastwf/interpolation

字符串插值库

1.1.0 2022-03-16 19:47 UTC

This package is auto-updated.

Last update: 2024-09-23 01:57:39 UTC


README

Quality Gate Status Unit tests Coverage

简介

字符串插值库。

对于所有示例,必须包含 vendor/autoload.php 以允许自动包含。

StringInterpolator

用法

<?php
// test.php
// ...

use Fastwf\Interpolation\StringInterpolator;

$interpolator = new StringInterpolator();

echo $interpolator->interpolate(
    "Hello %{name} with injection escaped \%{name} or %{undefined} not injected.",
    ['name' => 'Fast Web Framework']
) . PHP_EOL;

此脚本执行将生成以下输出。

$ php test.php
Hello Fast Web Framework with injection escaped %{name} or %{undefined} not injected.

自定义

可以自定义插值器的行为。

严格插值

插值可以是严格的,在这种情况下,如果参数数组中没有提供变量,则抛出 InterpolationException 异常。

<?php
///...
new StringInterpolator(true);

不同的标记

插值标记可以自定义。例如,使用 #[...] 而不是 %{...}

<?php
///...
new StringInterpolator(false, '#', '[', ']');

LexInterpolator

用法

<?php
// test.php
// ...

use Fastwf\Interpolation\LexInterpolator;


$interpolator = new LexInterpolator();

echo $interpolator->interpolate(
    "Hello %{name} with injection escaped \%{name}.",
    ['name' => 'Fast Web Framework']
) . PHP_EOL;

此脚本执行将生成以下输出。

$ php test.php
Hello Fast Web Framework with injection escaped \%{name}.

由于词法分析将模板解析为节点,并且节点无法从其原始形式恢复,因此无法像 StringInterpolator 那样注入未定义的变量。

添加转换函数

LexInterpolator 允许通过管道语法转换值。

当值无法转换为字符串或必须在注入之前更新值时,需要管道。
以下示例显示了如何格式化日期并在将其注入模板之前对其进行转换。

// test.php
// ...

$interpolator = new LexInterpolator();

$interpolator->getEnvironment()
    ->setPipe('date', new PipeFunction(
        function ($date, $format) {
            return $date->format($format);
        })
    )
    ->setPipe('lower', new PipeFunction(
        function ($str) {
            return mb_strtolower($str);
        }
    ))
    ;

echo $interpolator->interpolate(
    "Today is %{ today | date('l jS F Y') | lower }.",
    ['today' => new DateTime('2022-03-16')]
) . PHP_EOL;

此脚本执行将生成以下输出。

$ php test.php
Today is wednesday 16th march 2022.

自定义

StringInterpolator 类似,插值标记可以针对 LexInterpolator 进行自定义。

例如,对于 #[...]

<?php
// ...

$interpolator = new LexInterpolator("#", "[", "]");

// ...