Skip to content

Latest commit

 

History

History
91 lines (64 loc) · 3.08 KB

File metadata and controls

91 lines (64 loc) · 3.08 KB

PlaceholderFormatter Modifiers

Modifiers transform placeholder values before they're inserted into the final string. They're applied using the | syntax: {{placeholder|modifier}}.

How Modifiers Work

Modifiers form a chain where each modifier can:

  1. Handle the value and return a transformed string
  2. Pass the value to the next modifier in the chain

Chaining Multiple Modifiers

You can chain multiple modifiers together by separating them with the pipe (|) character. Modifiers are applied sequentially from left to right, with each modifier receiving the output of the previous one.

$formatter = new PlaceholderFormatter([
    'phone' => '1234567890',
    'value' => '123456',
]);

// Apply pattern formatting, then mask sensitive data
echo $formatter->format('Phone: {{phone|pattern:(###) ###-####|mask:6-12}}');
// Output: Phone: (123) ******90

// Escaped pipe in pattern argument, then apply mask
echo $formatter->format('{{value|pattern:###\|###|mask:1-3}}');
// Output: ***|456

Important: When using the pipe character (|) as part of a modifier argument (not as a separator), escape it with a backslash (\|).

Basic Usage

use Respect\StringFormatter\PlaceholderFormatter;

$formatter = new PlaceholderFormatter([
    'name' => 'John',
    'items' => ['apple', 'banana'],
]);

echo $formatter->format('Hello {{name}}');
// Output: Hello John

echo $formatter->format('Items: {{items}}');
// Output: Items: ["apple","banana"]

Custom Modifier Chain

You can specify a custom modifier chain when creating a PlaceholderFormatter:

use Respect\StringFormatter\PlaceholderFormatter;
use Respect\StringFormatter\Modifiers\RawModifier;
use Respect\StringFormatter\Modifiers\StringifyModifier;

$formatter = new PlaceholderFormatter(
    ['name' => 'John', 'active' => true],
    new RawModifier(new StringifyModifier()),
);

echo $formatter->format('Hello {{name}}');
// Output: Hello "John"

echo $formatter->format('Hello {{name|raw}}');
// Output: Hello John

If no modifier is provided, the formatter uses StringifyModifier by default.

Available Modifiers

Creating Custom Modifiers

See Creating Custom Modifiers for implementing your own modifiers.