Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| Interpolate | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
4 | |
100.00% |
1 / 1 |
| apply | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Celemas\Verba; |
| 6 | |
| 7 | /** |
| 8 | * Fills placeholders in a message template. |
| 9 | * |
| 10 | * A positional (list) args array is applied with `vsprintf`; a named |
| 11 | * (associative) args array replaces `:key` tokens. An empty args array |
| 12 | * leaves the template untouched, so literal `%` in named strings is safe. |
| 13 | * |
| 14 | * @api |
| 15 | */ |
| 16 | final class Interpolate |
| 17 | { |
| 18 | /** |
| 19 | * @param array<array-key, string|int|float> $args |
| 20 | */ |
| 21 | public static function apply(string $template, array $args): string |
| 22 | { |
| 23 | if ($args === []) { |
| 24 | return $template; |
| 25 | } |
| 26 | |
| 27 | if (array_is_list($args)) { |
| 28 | return vsprintf($template, $args); |
| 29 | } |
| 30 | |
| 31 | $pairs = []; |
| 32 | |
| 33 | /** @var array<array-key, string|int|float> $args */ |
| 34 | foreach ($args as $key => $value) { |
| 35 | $pairs[':' . $key] = (string) $value; |
| 36 | } |
| 37 | |
| 38 | return strtr($template, $pairs); |
| 39 | } |
| 40 | } |