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 unless method on stringable #37326

Merged
merged 2 commits into from
May 10, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 19 additions & 0 deletions src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,25 @@ public function ucfirst()
return new static(Str::ucfirst($this->value));
}

/**
* Apply the callback's string changes if the given "value" is false.
*
* @param mixed $value
* @param callable $callback
* @param callable|null $default
* @return mixed|$this
*/
public function unless($value, $callback, $default = null)
{
if (! $value) {
return $this->when(true, $callback);
} elseif ($default) {
return $this->when(false, $callback, $default);
}

return $this;
}
PH7-Jack marked this conversation as resolved.
Show resolved Hide resolved

/**
* Apply the callback's string changes if the given "value" is true.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportStringableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ public function testCanBeLimitedByWords()
$this->assertSame('Taylor Otwell', (string) $this->stringable('Taylor Otwell')->words(3));
}

public function testUnless()
{
$this->assertSame('unless false', (string) $this->stringable('unless')->unless(false, function ($stringable, $value) {
return $stringable->append(' false');
}));

$this->assertSame('unless true fallbacks to default', (string) $this->stringable('unless')->unless(true, function ($stringable, $value) {
return $stringable->append($value);
}, function ($stringable) {
return $stringable->append(' true fallbacks to default');
}));
}

public function testWhenEmpty()
{
tap($this->stringable(), function ($stringable) {
Expand Down