Skip to content

Commit 3abc4fb

Browse files
committed
Higher order tap.
This allows you to pass a single argument into tap, then call any method on that object, and return the object itself. I’ve found this primarily useful around Eloquent methods that I want to return $this…. For example: return tap($model)->update([‘foo’ => ‘bar’]);
1 parent ac03097 commit 3abc4fb

File tree

3 files changed

+49
-2
lines changed

3 files changed

+49
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Illuminate\Support;
4+
5+
class HigherOrderTapProxy
6+
{
7+
/**
8+
* The target being tapped.
9+
*
10+
* @var mixed
11+
*/
12+
public $target;
13+
14+
/**
15+
* Create a new tap proxy instance.
16+
*
17+
* @param mixed $target
18+
* @return void
19+
*/
20+
public function __construct($target)
21+
{
22+
$this->target = $target;
23+
}
24+
25+
/**
26+
* Dynamically pass method calls to the target.
27+
*
28+
* @param string $method
29+
* @param array $parameters
30+
* @return mixed
31+
*/
32+
public function __call($method, $parameters)
33+
{
34+
$this->target->{$method}(...$parameters);
35+
36+
return $this->target;
37+
}
38+
}

src/Illuminate/Support/helpers.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Illuminate\Support\Collection;
66
use Illuminate\Support\Debug\Dumper;
77
use Illuminate\Contracts\Support\Htmlable;
8+
use Illuminate\Support\HigherOrderTapProxy;
89

910
if (! function_exists('append_config')) {
1011
/**
@@ -870,11 +871,15 @@ function studly_case($value)
870871
* Call the given Closure with the given value then return the value.
871872
*
872873
* @param mixed $value
873-
* @param callable $callback
874+
* @param callable|null $callback
874875
* @return mixed
875876
*/
876-
function tap($value, $callback)
877+
function tap($value, $callback = null)
877878
{
879+
if (is_null($callback)) {
880+
return new HigherOrderTapProxy($value);
881+
}
882+
878883
$callback($value);
879884

880885
return $value;

tests/Support/SupportHelpersTest.php

+4
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,10 @@ public function testTap()
705705
$this->assertEquals(2, tap($object, function ($object) {
706706
$object->id = 2;
707707
})->id);
708+
709+
$mock = m::mock();
710+
$mock->shouldReceive('foo')->once()->andReturn('bar');
711+
$this->assertEquals($mock, tap($mock)->foo());
708712
}
709713
}
710714

0 commit comments

Comments
 (0)