Skip to content

Commit

Permalink
GlobalFunction, Method: from() accepts first-class callables
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Mar 19, 2024
1 parent b135071 commit c0a147f
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/PhpGenerator/GlobalFunction.php
Expand Up @@ -9,6 +9,8 @@

namespace Nette\PhpGenerator;

use Nette;


/**
* Global function.
Expand All @@ -20,9 +22,9 @@ final class GlobalFunction
use Traits\CommentAware;
use Traits\AttributeAware;

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


Expand Down
2 changes: 1 addition & 1 deletion src/PhpGenerator/Method.php
Expand Up @@ -28,7 +28,7 @@ final class Method
private bool $abstract = false;


public static function from(string|array $method): static
public static function from(string|array|\Closure $method): static
{
return (new Factory)->fromMethodReflection(Nette\Utils\Callback::toReflection($method));
}
Expand Down
36 changes: 36 additions & 0 deletions tests/PhpGenerator/GlobalFunction.from.81.phpt
@@ -0,0 +1,36 @@
<?php

/**
* @phpVersion 8.1
*/

declare(strict_types=1);

use Nette\PhpGenerator\GlobalFunction;

require __DIR__ . '/../bootstrap.php';


/** global */
#[ExampleAttribute]
function func(stdClass $a, $b = null)
{
echo sprintf('hello, %s', 'world');
return 1;
}


$function = GlobalFunction::from(func(...));
same(
<<<'XX'
/**
* global
*/
#[ExampleAttribute]
function func(stdClass $a, $b = null)
{
}
XX,
(string) $function,
);
30 changes: 30 additions & 0 deletions tests/PhpGenerator/Method.from.81.phpt
@@ -0,0 +1,30 @@
<?php

/**
* @phpVersion 8.1
*/

declare(strict_types=1);

use Nette\PhpGenerator\Method;

require __DIR__ . '/../bootstrap.php';


class Foo
{
public static function bar(int $a, ...$b): void
{
}
}

$method = Method::from(Foo::bar(...));
same(
<<<'XX'
public static function bar(int $a, ...$b): void
{
}
XX,
(string) $method,
);

0 comments on commit c0a147f

Please sign in to comment.