Skip to content

Commit c658d14

Browse files
authored
Allow default values when merging values into a resource (#48073)
1 parent 8e148dc commit c658d14

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,23 +140,31 @@ protected function merge($value)
140140
*
141141
* @param bool $condition
142142
* @param mixed $value
143+
* @param mixed $default
143144
* @return \Illuminate\Http\Resources\MergeValue|mixed
144145
*/
145-
protected function mergeWhen($condition, $value)
146+
protected function mergeWhen($condition, $value, $default = null)
146147
{
147-
return $condition ? new MergeValue(value($value)) : new MissingValue;
148+
if ($condition) {
149+
return new MergeValue(value($value));
150+
}
151+
152+
return func_num_args() === 3 ? new MergeValue(value($default)) : new MissingValue();
148153
}
149154

150155
/**
151156
* Merge a value unless the given condition is truthy.
152157
*
153158
* @param bool $condition
154159
* @param mixed $value
160+
* @param mixed $default
155161
* @return \Illuminate\Http\Resources\MergeValue|mixed
156162
*/
157-
protected function mergeUnless($condition, $value)
163+
protected function mergeUnless($condition, $value, $default = null)
158164
{
159-
return ! $condition ? new MergeValue(value($value)) : new MissingValue;
165+
$arguments = func_num_args() === 2 ? [$value] : [$value, $default];
166+
167+
return $this->mergeWhen(! $condition, ...$arguments);
160168
}
161169

162170
/**

tests/Integration/Http/ResourceTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1598,6 +1598,29 @@ public function work()
15981598
], $results);
15991599
}
16001600

1601+
public function testMergeValuesMayFallbackToDefaults()
1602+
{
1603+
$filter = new class
1604+
{
1605+
use ConditionallyLoadsAttributes;
1606+
1607+
public function work()
1608+
{
1609+
return $this->filter([
1610+
$this->mergeUnless(false, ['Taylor', 'Mohamed'], ['First', 'Second']),
1611+
$this->mergeWhen(false, ['Adam', 'Matt'], ['Abigail', 'Lydia']),
1612+
'Jeffrey',
1613+
]);
1614+
}
1615+
};
1616+
1617+
$results = $filter->work();
1618+
1619+
$this->assertEquals([
1620+
'Taylor', 'Mohamed', 'Abigail', 'Lydia', 'Jeffrey',
1621+
], $results);
1622+
}
1623+
16011624
public function testNestedMerges()
16021625
{
16031626
$filter = new class

0 commit comments

Comments
 (0)