|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
* This file is part of StringTemplate. |
|
4
|
|
|
* |
|
5
|
|
|
* (c) 2013 Nicolò Martini |
|
6
|
|
|
* |
|
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
8
|
|
|
* file that was distributed with this source code. |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace StringTemplate; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Class Engine |
|
15
|
|
|
* |
|
16
|
|
|
* Replace placeholder in strings with nested (array) values, allowing an optional |
|
17
|
|
|
* sprintf-like parameter after the placeholder name. |
|
18
|
|
|
* |
|
19
|
|
|
* Example: |
|
20
|
|
|
* <code> |
|
21
|
|
|
* $engine->render('This is {a} and these are {c.0%E} and {c.1}', ['a' => 'b', 'c' => [1, 'e']]); |
|
22
|
|
|
* //Prints "This is b and these are d and 1.000000E+0" |
|
23
|
|
|
* </code> |
|
24
|
|
|
*/ |
|
25
|
|
|
class SprintfEngine extends Engine |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* {@inheritdoc} |
|
29
|
|
|
*/ |
|
30
|
|
|
public function render($template, $value) |
|
31
|
|
|
{ |
|
32
|
|
|
//Performance: if there are no '%' fallback to Engine |
|
33
|
|
|
if (strstr($template, '%') == false) { |
|
|
|
|
|
|
34
|
|
|
return parent::render($template, $value); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$result = $template; |
|
38
|
|
|
if (!is_array($value)) |
|
39
|
|
|
$value = array('' => $value); |
|
40
|
|
|
|
|
41
|
|
|
foreach (new NestedKeyIterator(new RecursiveArrayOnlyIterator($value)) as $key => $value) { |
|
42
|
|
|
$pattern = "/" . $this->left . $key . "(%[^" . $this->right . "]+)?" . $this->right . "/"; |
|
43
|
|
|
preg_match_all($pattern, $template, $matches); |
|
44
|
|
|
$substs = array_map(function ($match) use ($value) { |
|
45
|
|
|
return $match !== '' ? sprintf($match, $value) : $value; |
|
46
|
|
|
}, $matches[1]); |
|
47
|
|
|
$result = str_replace($matches[0], $substs, $result); |
|
48
|
|
|
} |
|
49
|
|
|
return $result; |
|
50
|
|
|
} |
|
51
|
|
|
} |