From e7aed89e8f86b7a26ccfff816bdde996765108d7 Mon Sep 17 00:00:00 2001 From: Alexander Skvortsov <38059171+askvortsov1@users.noreply.github.com> Date: Wed, 10 Feb 2021 14:51:31 -0500 Subject: [PATCH] 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. --- src/Foundation/ContainerUtil.php | 4 +-- tests/unit/Foundation/ContainerUtilTest.php | 28 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/Foundation/ContainerUtil.php b/src/Foundation/ContainerUtil.php index 1c5b95972..acc571bd5 100644 --- a/src/Foundation/ContainerUtil.php +++ b/src/Foundation/ContainerUtil.php @@ -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); diff --git a/tests/unit/Foundation/ContainerUtilTest.php b/tests/unit/Foundation/ContainerUtilTest.php index 96723ecb4..3630b204f 100644 --- a/tests/unit/Foundation/ContainerUtilTest.php +++ b/tests/unit/Foundation/ContainerUtilTest.php @@ -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'; + } +}