Permalink
Browse files

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’]);
  • Loading branch information...
taylorotwell committed Apr 19, 2017
1 parent ac03097 commit 3abc4fb90fe59a90c2d8cccd27e310b20e5e2631
@@ -0,0 +1,38 @@
<?php
namespace Illuminate\Support;
class HigherOrderTapProxy
{
/**
* The target being tapped.
*
* @var mixed
*/
public $target;
/**
* Create a new tap proxy instance.
*
* @param mixed $target
* @return void
*/
public function __construct($target)
{
$this->target = $target;
}
/**
* Dynamically pass method calls to the target.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
$this->target->{$method}(...$parameters);
return $this->target;
}
}
@@ -5,6 +5,7 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Debug\Dumper;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\HigherOrderTapProxy;
if (! function_exists('append_config')) {
/**
@@ -870,11 +871,15 @@ function studly_case($value)
* Call the given Closure with the given value then return the value.
*
* @param mixed $value
* @param callable $callback
* @param callable|null $callback
* @return mixed
*/
function tap($value, $callback)
function tap($value, $callback = null)
{
if (is_null($callback)) {
return new HigherOrderTapProxy($value);
}
$callback($value);
return $value;
@@ -705,6 +705,10 @@ public function testTap()
$this->assertEquals(2, tap($object, function ($object) {
$object->id = 2;
})->id);
$mock = m::mock();
$mock->shouldReceive('foo')->once()->andReturn('bar');
$this->assertEquals($mock, tap($mock)->foo());
}
}

0 comments on commit 3abc4fb

Please sign in to comment.