Skip to content

Commit 929bf71

Browse files
committed
Helpers::expand supports concatenation of PhpLiteral
1 parent 7113e45 commit 929bf71

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

src/DI/Helpers.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,14 @@ public static function expand($var, array $params, $recursive = FALSE)
4444
}
4545

4646
$parts = preg_split('#%([\w.-]*)%#i', $var, -1, PREG_SPLIT_DELIM_CAPTURE);
47-
$res = '';
47+
$res = [];
48+
$php = FALSE;
4849
foreach ($parts as $n => $part) {
4950
if ($n % 2 === 0) {
50-
$res .= $part;
51+
$res[] = $part;
5152

5253
} elseif ($part === '') {
53-
$res .= '%';
54+
$res[] = '%';
5455

5556
} elseif (isset($recursive[$part])) {
5657
throw new Nette\InvalidArgumentException(sprintf('Circular reference detected for variables: %s.', implode(', ', array_keys($recursive))));
@@ -67,13 +68,20 @@ public static function expand($var, array $params, $recursive = FALSE)
6768
if (strlen($part) + 2 === strlen($var)) {
6869
return $val;
6970
}
70-
if (!is_scalar($val)) {
71+
if ($val instanceof Nette\PhpGenerator\PhpLiteral) {
72+
$php = TRUE;
73+
} elseif (!is_scalar($val)) {
7174
throw new Nette\InvalidArgumentException("Unable to concatenate non-scalar parameter '$part' into '$var'.");
7275
}
73-
$res .= $val;
76+
$res[] = $val;
7477
}
7578
}
76-
return $res;
79+
if ($php) {
80+
$res = array_filter($res, function ($val) { return $val !== ''; });
81+
$res = array_map(function ($val) { return is_string($val) ? var_export($val, TRUE) : $val; }, $res);
82+
return new Nette\PhpGenerator\PhpLiteral(implode(' . ', $res));
83+
}
84+
return implode('', $res);
7785
}
7886

7987

tests/DI/Helpers.expand().phpt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66

77
use Nette\DI\Helpers;
8+
use Nette\PhpGenerator\PhpLiteral;
89
use Tester\Assert;
910

1011

@@ -28,6 +29,11 @@ Assert::same(
2829
], TRUE)
2930
);
3031

32+
Assert::equal(new PhpLiteral('func()'), Helpers::expand('%key%', ['key' => new PhpLiteral('func()')]));
33+
Assert::equal(new PhpLiteral("'text' . func()"), Helpers::expand('text%key%', ['key' => new PhpLiteral('func()')]));
34+
Assert::equal(new PhpLiteral("func() . 'text'"), Helpers::expand('%key%text', ['key' => new PhpLiteral('func()')]));
35+
Assert::equal(new PhpLiteral("'a' . func() . 'b' . 123 . func() . 'c'"), Helpers::expand('a%key1%b%key2%%key1%c', ['key1' => new PhpLiteral('func()'), 'key2' => 123]));
36+
3137

3238
Assert::exception(function () {
3339
Helpers::expand('%missing%', []);

0 commit comments

Comments
 (0)