Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add Str::pipe & make Stringable tappable #36017

Merged
merged 2 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

use Closure;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\Tappable;
use Symfony\Component\VarDumper\VarDumper;

class Stringable
{
use Macroable;
use Tappable, Macroable;

/**
* The underlying string value.
Expand Down Expand Up @@ -399,6 +400,17 @@ public function parseCallback($default = null)
return Str::parseCallback($this->value, $default);
}

/**
* Call the given callback and return a new string.
*
* @param callable $callback
* @return static
*/
public function pipe(callable $callback)
{
return new static(call_user_func($callback, $this));
}

/**
* Get the plural form of an English word.
*
Expand Down
24 changes: 24 additions & 0 deletions tests/Support/SupportStringableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -545,4 +545,28 @@ public function testChunk()
$this->assertInstanceOf(Collection::class, $chunks);
$this->assertSame(['foo', 'bar', 'baz'], $chunks->all());
}

public function testTap()
{
$stringable = $this->stringable('foobarbaz');

$fromTheTap = '';

$stringable = $stringable->tap(function (Stringable $string) use (&$fromTheTap) {
$fromTheTap = $string->substr(0, 3);
});

$this->assertSame('foo', (string) $fromTheTap);
$this->assertSame('foobarbaz', (string) $stringable);
}

public function testPipe()
{
$callback = function ($stringable) {
return 'bar';
};

$this->assertInstanceOf(Stringable::class, $this->stringable('foo')->pipe($callback));
$this->assertSame('bar', (string) $this->stringable('foo')->pipe($callback));
}
}