From 8dcb2f2a0845028746d83a47c845200eb26099bd Mon Sep 17 00:00:00 2001 From: Choraimy Kroonstuiver <3661474+axlon@users.noreply.github.com> Date: Tue, 15 Aug 2023 14:55:52 +0200 Subject: [PATCH] Allow default values when merging values into a resource --- .../ConditionallyLoadsAttributes.php | 16 +++++++++---- tests/Integration/Http/ResourceTest.php | 23 +++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php b/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php index dfcc202229fd..3f25ca052407 100644 --- a/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php +++ b/src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php @@ -140,11 +140,16 @@ protected function merge($value) * * @param bool $condition * @param mixed $value + * @param mixed $default * @return \Illuminate\Http\Resources\MergeValue|mixed */ - protected function mergeWhen($condition, $value) + protected function mergeWhen($condition, $value, $default = null) { - return $condition ? new MergeValue(value($value)) : new MissingValue; + if ($condition) { + return new MergeValue(value($value)); + } + + return func_num_args() === 3 ? new MergeValue(value($default)) : new MissingValue(); } /** @@ -152,11 +157,14 @@ protected function mergeWhen($condition, $value) * * @param bool $condition * @param mixed $value + * @param mixed $default * @return \Illuminate\Http\Resources\MergeValue|mixed */ - protected function mergeUnless($condition, $value) + protected function mergeUnless($condition, $value, $default = null) { - return ! $condition ? new MergeValue(value($value)) : new MissingValue; + $arguments = func_num_args() === 2 ? [$value] : [$value, $default]; + + return $this->mergeWhen(! $condition, ...$arguments); } /** diff --git a/tests/Integration/Http/ResourceTest.php b/tests/Integration/Http/ResourceTest.php index 9e8ee81f5841..d4217efecddc 100644 --- a/tests/Integration/Http/ResourceTest.php +++ b/tests/Integration/Http/ResourceTest.php @@ -1598,6 +1598,29 @@ public function work() ], $results); } + public function testMergeValuesMayFallbackToDefaults() + { + $filter = new class + { + use ConditionallyLoadsAttributes; + + public function work() + { + return $this->filter([ + $this->mergeUnless(false, ['Taylor', 'Mohamed'], ['First', 'Second']), + $this->mergeWhen(false, ['Adam', 'Matt'], ['Abigail', 'Lydia']), + 'Jeffrey', + ]); + } + }; + + $results = $filter->work(); + + $this->assertEquals([ + 'Taylor', 'Mohamed', 'Abigail', 'Lydia', 'Jeffrey', + ], $results); + } + public function testNestedMerges() { $filter = new class