Broader support for callables in ContainerUtil (#2596)

It can be very annoying if we want to use something like boolval, but have to define an entire anonymous function to pass it in. This PR adds support for tpassing it in directly as a string, like is posible with User::registerPreference.
This commit is contained in:
Alexander Skvortsov 2021-02-10 14:51:31 -05:00 committed by GitHub
parent f2271311c5
commit 7e3b83b4f6
2 changed files with 30 additions and 2 deletions

View File

@ -18,12 +18,12 @@ class ContainerUtil
*
* @internal Backwards compatability not guaranteed.
*
* @param callable|string $callback: A callable, or a ::class attribute of an invokable class
* @param callable|string $callback: A callable, global function, or a ::class attribute of an invokable class
* @param Container $container
*/
public static function wrapCallback($callback, Container $container)
{
if (is_string($callback)) {
if (is_string($callback) && ! is_callable($callback)) {
$callback = function (&...$args) use ($container, $callback) {
$callback = $container->make($callback);

View File

@ -74,6 +74,26 @@ class ContainerUtilTest extends TestCase
$this->assertEquals('return5', $return);
}
/** @test */
public function it_works_with_global_functions()
{
$callback = ContainerUtil::wrapCallback('boolval', $this->container);
$this->assertEquals(true, $callback(true));
$this->assertEquals(true, $callback(1));
$this->assertEquals(true, $callback('1'));
$this->assertEquals(false, $callback(0));
$this->assertEquals(false, $callback(false));
}
/** @test */
public function it_works_with_static_class_method_arrays()
{
$callback = ContainerUtil::wrapCallback([ClassWithMethod::class, 'staticMethod'], $this->container);
$this->assertEquals('returnStatic', $callback());
}
/** @test */
public function it_allows_passing_args_by_reference_on_closures()
{
@ -141,3 +161,11 @@ class SecondCustomInvokableClass
return 'return4';
}
}
class ClassWithMethod
{
public static function staticMethod()
{
return 'returnStatic';
}
}