Skip to content

Commit 6b873e7

Browse files
committed
added Printer::printArrowFunction()
1 parent 4108441 commit 6b873e7

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

readme.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,27 @@ function ($a, $b) use (&$c) {
335335
}
336336
```
337337

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+
338359
Method and Function Body Generator
339360
----------------------------------
340361

src/PhpGenerator/Printer.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,22 @@ public function printClosure(Closure $closure): string
6161
}
6262

6363

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+
6480
public function printMethod(Method $method, PhpNamespace $namespace = null): string
6581
{
6682
$method->validate();
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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.');

0 commit comments

Comments
 (0)