mirror of
https://github.com/flarum/framework.git
synced 2024-11-26 02:10:09 +08:00
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:
parent
f2271311c5
commit
7e3b83b4f6
|
@ -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);
|
||||
|
||||
|
|
|
@ -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';
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user