File tree Expand file tree Collapse file tree 3 files changed +75
-0
lines changed Expand file tree Collapse file tree 3 files changed +75
-0
lines changed Original file line number Diff line number Diff line change @@ -335,6 +335,27 @@ function ($a, $b) use (&$c) {
335
335
}
336
336
```
337
337
338
+ Arrow function
339
+ --------------
340
+
341
+ You can also print closure as arrow function using printer:
342
+
343
+ ``` php
344
+ $closure = new Nette\PhpGenerator\Closure;
345
+ $closure->setBody('return $a + $b;');
346
+ $closure->addParameter('a');
347
+ $closure->addParameter('b');
348
+
349
+ // or use PsrPrinter for output compatible with PSR-2 / PSR-12
350
+ echo (new Nette\PhpGenerator\Printer)->printArrowFunction($closure);
351
+ ```
352
+
353
+ Result:
354
+
355
+ ``` php
356
+ fn ($a, $b) => $a + $b;
357
+ ```
358
+
338
359
Method and Function Body Generator
339
360
----------------------------------
340
361
Original file line number Diff line number Diff line change @@ -61,6 +61,22 @@ public function printClosure(Closure $closure): string
61
61
}
62
62
63
63
64
+ public function printArrowFunction (Closure $ closure ): string
65
+ {
66
+ foreach ($ closure ->getUses () as $ use ) {
67
+ if ($ use ->isReference ()) {
68
+ throw new Nette \InvalidArgumentException ('Arrow function cannot bind variables by-reference. ' );
69
+ }
70
+ }
71
+
72
+ return 'fn '
73
+ . ($ closure ->getReturnReference () ? '& ' : '' )
74
+ . $ this ->printParameters ($ closure , null )
75
+ . $ this ->printReturnType ($ closure , null )
76
+ . ' => ' . trim ($ closure ->getBody ()) . '; ' ;
77
+ }
78
+
79
+
64
80
public function printMethod (Method $ method , PhpNamespace $ namespace = null ): string
65
81
{
66
82
$ method ->validate ();
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types=1 );
4
+
5
+ use Nette \PhpGenerator \Closure ;
6
+ use Nette \PhpGenerator \Printer ;
7
+ use Tester \Assert ;
8
+
9
+
10
+ require __DIR__ . '/../bootstrap.php ' ;
11
+
12
+
13
+ $ function = new Closure ;
14
+ $ function
15
+ ->setReturnReference (true )
16
+ ->setBody ('$a + $b ' );
17
+
18
+ $ function ->addParameter ('a ' );
19
+ $ function ->addParameter ('b ' );
20
+
21
+ Assert::same ('fn &($a, $b) => $a + $b; ' , (new Printer )->printArrowFunction ($ function ));
22
+
23
+
24
+
25
+ $ function = new Closure ;
26
+ $ function
27
+ ->setReturnType ('array ' )
28
+ ->setBody ('[] ' );
29
+
30
+ Assert::same ('fn (): array => []; ' , (new Printer )->printArrowFunction ($ function ));
31
+
32
+
33
+ Assert::exception (function () {
34
+ $ function = new Closure ;
35
+ $ function ->addUse ('vars ' )
36
+ ->setReference (true );
37
+ (new Printer )->printArrowFunction ($ function );
38
+ }, Nette \InvalidArgumentException::class, 'Arrow function cannot bind variables by-reference. ' );
You can’t perform that action at this time.
0 commit comments