Skip to content

Commit 78dcebd

Browse files
committed
GlobalFunction, Method: from() accepts first-class callables
1 parent 0c4df0d commit 78dcebd

File tree

4 files changed

+71
-3
lines changed

4 files changed

+71
-3
lines changed

src/PhpGenerator/GlobalFunction.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
namespace Nette\PhpGenerator;
1111

12+
use Nette;
13+
1214

1315
/**
1416
* Global function.
@@ -20,9 +22,9 @@ final class GlobalFunction
2022
use Traits\CommentAware;
2123
use Traits\AttributeAware;
2224

23-
public static function from(string $function, bool $withBody = false): self
25+
public static function from(string|\Closure $function, bool $withBody = false): self
2426
{
25-
return (new Factory)->fromFunctionReflection(new \ReflectionFunction($function), $withBody);
27+
return (new Factory)->fromFunctionReflection(Nette\Utils\Callback::toReflection($function), $withBody);
2628
}
2729

2830

src/PhpGenerator/Method.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ final class Method
2828
private bool $abstract = false;
2929

3030

31-
public static function from(string|array $method): static
31+
public static function from(string|array|\Closure $method): static
3232
{
3333
return (new Factory)->fromMethodReflection(Nette\Utils\Callback::toReflection($method));
3434
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/**
4+
* @phpVersion 8.1
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\PhpGenerator\GlobalFunction;
10+
11+
require __DIR__ . '/../bootstrap.php';
12+
13+
14+
/** global */
15+
#[ExampleAttribute]
16+
function func(stdClass $a, $b = null)
17+
{
18+
echo sprintf('hello, %s', 'world');
19+
return 1;
20+
}
21+
22+
23+
$function = GlobalFunction::from(func(...));
24+
same(
25+
<<<'XX'
26+
/**
27+
* global
28+
*/
29+
#[ExampleAttribute]
30+
function func(stdClass $a, $b = null)
31+
{
32+
}
33+
34+
XX,
35+
(string) $function,
36+
);
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/**
4+
* @phpVersion 8.1
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\PhpGenerator\Method;
10+
11+
require __DIR__ . '/../bootstrap.php';
12+
13+
14+
class Foo
15+
{
16+
public static function bar(int $a, ...$b): void
17+
{
18+
}
19+
}
20+
21+
$method = Method::from(Foo::bar(...));
22+
same(
23+
<<<'XX'
24+
public static function bar(int $a, ...$b): void
25+
{
26+
}
27+
28+
XX,
29+
(string) $method,
30+
);

0 commit comments

Comments
 (0)