forked from Respect/StringFormatter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatterModifier.php
More file actions
63 lines (50 loc) · 1.58 KB
/
FormatterModifier.php
File metadata and controls
63 lines (50 loc) · 1.58 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
<?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\Modifiers;
use Respect\StringFormatter\Formatter;
use Respect\StringFormatter\FormatterBuilder;
use Respect\StringFormatter\Modifier;
use Throwable;
use function array_shift;
use function assert;
use function is_scalar;
use function is_string;
use function preg_split;
final readonly class FormatterModifier implements Modifier
{
public function __construct(
private Modifier $nextModifier,
) {
}
public function modify(mixed $value, string|null $pipe): string
{
if ($pipe === null) {
return $this->nextModifier->modify($value, $pipe);
}
$arguments = preg_split('/(?<!\\\\):/', $pipe) ?: [];
$name = array_shift($arguments);
assert(is_string($name));
$formatter = $this->tryToCreateFormatter($name, $arguments);
if ($formatter === null) {
return $this->nextModifier->modify($value, $pipe);
}
if (!is_scalar($value)) {
return $this->nextModifier->modify($value, null);
}
return $formatter->format((string) $value);
}
/** @param array<int, string> $arguments */
private function tryToCreateFormatter(string $name, array $arguments): Formatter|null
{
try {
return FormatterBuilder::__callStatic($name, $arguments);
} catch (Throwable) {
return null;
}
}
}