forked from Respect/StringFormatter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlaceholderFormatter.php
More file actions
84 lines (70 loc) · 2.47 KB
/
PlaceholderFormatter.php
File metadata and controls
84 lines (70 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-License-Identifier: ISC
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/
declare(strict_types=1);
namespace Respect\StringFormatter;
use Respect\StringFormatter\Modifiers\FormatterModifier;
use Respect\StringFormatter\Modifiers\ListModifier;
use Respect\StringFormatter\Modifiers\StringifyModifier;
use Respect\StringFormatter\Modifiers\StringPassthroughModifier;
use Respect\StringFormatter\Modifiers\TransModifier;
use function array_key_exists;
use function preg_replace_callback;
use function preg_split;
final readonly class PlaceholderFormatter implements Formatter
{
/** @param array<string, mixed> $parameters */
public function __construct(
private array $parameters,
private Modifier $modifier = new TransModifier(
new ListModifier(
new FormatterModifier(new StringPassthroughModifier(new StringifyModifier())),
),
),
) {
}
public function format(string $input): string
{
return $this->formatUsingParameters($input, $this->parameters);
}
/** @param array<string, mixed> $parameters */
public function formatUsing(string $input, array $parameters): string
{
return $this->formatUsingParameters($input, $this->parameters + $parameters);
}
/** @param array<string, mixed> $parameters */
private function formatUsingParameters(string $input, array $parameters): string
{
return (string) preg_replace_callback(
'/{{(\w+)(\|([^}\\\\]*(?:\\\\.[^}\\\\]*)*))?}}/',
fn(array $matches) => $this->processPlaceholder($matches, $parameters),
$input,
);
}
/**
* @param array<int, string> $matches
* @param array<string, mixed> $parameters
*/
private function processPlaceholder(array $matches, array $parameters): string
{
$placeholder = $matches[0] ?? '';
$name = $matches[1] ?? '';
$pipe = $matches[3] ?? null;
if (!array_key_exists($name, $parameters)) {
return $placeholder;
}
$value = $parameters[$name];
if ($pipe === null) {
return $this->modifier->modify($value, null);
}
$pipes = preg_split('/(?<!\\\\)\|/', $pipe) ?: [];
foreach ($pipes as $pipe) {
$value = $this->modifier->modify($value, $pipe);
}
/** @phpstan-ignore return.type */
return $value;
}
}