Skip to content

Commit 36ac97d

Browse files
committed
Add Function.bindKey function
1 parent c009a89 commit 36ac97d

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/Function/bindKey.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
namespace _;
13+
14+
/**
15+
* Creates a function that invokes the method `$function` of `$object` with `$partials`
16+
* prepended to the arguments it receives.
17+
*
18+
* This method differs from `bind` by allowing bound functions to reference
19+
* methods that may be redefined or don't yet exist
20+
*
21+
* @category Function
22+
*
23+
* @param object|mixed $object The object to invoke the method on.
24+
* @param string $function The name of the method.
25+
* @param mixed[] $partials The arguments to be partially applied.
26+
*
27+
* @return callable Returns the new bound function.
28+
* @example
29+
*
30+
* $object = new class {
31+
* private $user = 'fred';
32+
* function greet($greeting, $punctuation) {
33+
* return $greeting.' '.$this->user.$punctuation;
34+
* }
35+
* };
36+
*
37+
* $bound = bindKey($object, 'greet', 'hi');
38+
* $bound('!');
39+
* // => 'hi fred!'
40+
*/
41+
function bindKey($object, string $function, ...$partials): callable
42+
{
43+
return function (...$args) use ($object, $function, $partials) {
44+
$function = \Closure::fromCallable([$object, $function])->bindTo($object, get_class($object));
45+
46+
return $function(...array_merge($partials, $args));
47+
};
48+
}

tests/Function/BindKeyTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
use PHPUnit\Framework\TestCase;
13+
use function _\bindKey;
14+
15+
class BindKeyTest extends TestCase
16+
{
17+
public function testBindKey()
18+
{
19+
$object = new class
20+
{
21+
private $user = 'fred';
22+
23+
function greet($greeting, $punctuation)
24+
{
25+
return $greeting.' '.$this->user.$punctuation;
26+
}
27+
};
28+
29+
$bound = bindKey($object, 'greet', 'hi');
30+
31+
$this->assertSame('hi fred!', $bound('!'));
32+
}
33+
}

0 commit comments

Comments
 (0)