Skip to content

Commit

Permalink
Higher order tap.
Browse files Browse the repository at this point in the history
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 3abc4fb
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
38 changes: 38 additions & 0 deletions src/Illuminate/Support/HigherOrderTapProxy.php
Original file line number Diff line number Diff line change
@@ -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;
}
}
9 changes: 7 additions & 2 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')) {
/**
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 4 additions & 0 deletions tests/Support/SupportHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}

Expand Down

0 comments on commit 3abc4fb

Please sign in to comment.