Skip to content

Commit 2f28a34

Browse files
committed
Literal: accepts parameters
1 parent 4e7be9e commit 2f28a34

File tree

5 files changed

+17
-5
lines changed

5 files changed

+17
-5
lines changed

readme.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ It is possible to add a comment or [attributes](#attributes) to each case using
272272
Literals
273273
--------
274274

275-
You can pass any PHP code to property or parameter default values via `Literal`:
275+
With `Literal` you can pass arbitrary PHP code to, for example, default property or parameter values etc:
276276

277277
```php
278278
use Nette\PhpGenerator\Literal;
@@ -300,6 +300,15 @@ class Demo
300300
}
301301
```
302302

303+
You can also pass parameters to `Literal` and have it formatted into valid PHP code using [special placeholders](#method-and-function-body-generator):
304+
305+
```php
306+
new Literal('substr(?, ?)', [$a, $b]);
307+
// generates, for example: substr('hello', 5);
308+
```
309+
310+
311+
303312
Using Traits
304313
------------
305314

src/PhpGenerator/Literal.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ class Literal
1919
private $value;
2020

2121

22-
public function __construct(string $value)
22+
public function __construct(string $value, array $args = null)
2323
{
24-
$this->value = $value;
24+
$this->value = $args === null
25+
? $value
26+
: (new Dumper)->format($value, ...$args);
2527
}
2628

2729

tests/PhpGenerator/ClassType.promotion.phpt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ $method->addPromotedParameter('c')
1919
->addComment('promo')
2020
->addAttribute('Example');
2121

22-
$method->addPromotedParameter('d', new Literal('new Draft'))
22+
$method->addPromotedParameter('d', new Literal('new Draft(?)', [10]))
2323
->setType('Draft')
2424
->setReadOnly();
2525

tests/PhpGenerator/Dumper.dump().phpt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ Assert::same('\'He\ll\\\\\o \\\'wor\\\\\\\'ld\\\\\'', $dumper->dump('He\ll\\\o \
4444

4545
// literal
4646
Assert::same('[$s]', $dumper->dump([new Literal('$s')]));
47+
Assert::same("[strlen('hello')]", $dumper->dump([new Literal('strlen(?)', ['hello'])]));
4748
same('[
4849
function () {
4950
return 1;

tests/PhpGenerator/expected/ClassType.promotion.expect

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ class Example
55
public $b,
66
/** promo */
77
#[Example] private string $c,
8-
public readonly Draft $d = new Draft,
8+
public readonly Draft $d = new Draft(10),
99
) {
1010
}
1111
}

0 commit comments

Comments
 (0)