Skip to content

Commit 8225119

Browse files
ManojKiranAManojKiran
andauthored
add when method to Stringable class (#33455)
Co-authored-by: ManojKiran <[email protected]>
1 parent 15c9af2 commit 8225119

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/Illuminate/Support/Stringable.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,25 @@ public function ucfirst()
600600
return new static(Str::ucfirst($this->value));
601601
}
602602

603+
/**
604+
* Apply the callback's string changes if the given "value" is true.
605+
*
606+
* @param mixed $value
607+
* @param callable $callback
608+
* @param callable|null $default
609+
* @return mixed|$this
610+
*/
611+
public function when($value, $callback, $default = null)
612+
{
613+
if ($value) {
614+
return $callback($this, $value) ?: $this;
615+
} elseif ($default) {
616+
return $default($this, $value) ?: $this;
617+
}
618+
619+
return $this;
620+
}
621+
603622
/**
604623
* Execute the given callback if the string is empty.
605624
*

tests/Support/SupportStringableTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,32 @@ public function testWhenEmpty()
9292
}));
9393
}
9494

95+
public function testWhenFalse()
96+
{
97+
$this->assertSame('when', (string) $this->stringable('when')->when(false,function($stringable,$value){
98+
return $stringable->append($value)->append('false');
99+
}));
100+
101+
$this->assertSame('when false fallbacks to default', (string) $this->stringable('when false ')->when(false,function($stringable,$value){
102+
return $stringable->append($value);
103+
},function($stringable){
104+
return $stringable->append('fallbacks to default');
105+
}));
106+
}
107+
108+
public function testWhenTrue()
109+
{
110+
$this->assertSame('when true', (string) $this->stringable('when ')->when(true,function($stringable){
111+
return $stringable->append('true');
112+
}));
113+
114+
$this->assertSame('gets a value from if', (string) $this->stringable('gets a value ')->when('from if',function($stringable,$value){
115+
return $stringable->append($value);
116+
},function($stringable){
117+
return $stringable->append('fallbacks to default');
118+
}));
119+
}
120+
95121
public function testTrimmedOnlyWhereNecessary()
96122
{
97123
$this->assertSame(' Taylor Otwell ', (string) $this->stringable(' Taylor Otwell ')->words(3));

0 commit comments

Comments
 (0)