Skip to content

Commit 4b6733c

Browse files
feat: add mergeWhenStateIn and mergeUnlessStateIn methods
1 parent 5075611 commit 4b6733c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/Concerns/StatefullyLoadsAttributes.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,48 @@ protected function mergeUnlessState($state, $value, $default = null)
130130
return $this->mergeUnless($this->getState() === $state, $value);
131131
}
132132

133+
/**
134+
* Merge a value if the current state is one of the given states.
135+
*
136+
* @param array<string|ResourceState> $states
137+
* @param mixed $value
138+
* @param mixed $default
139+
* @return \Illuminate\Http\Resources\MergeValue|mixed
140+
*/
141+
protected function mergeWhenStateIn(array $states, $value, $default = null)
142+
{
143+
$states = array_map(fn ($state) => $this->resolveState($state), $states);
144+
145+
$condition = in_array($this->getState(), $states, true);
146+
147+
if (func_num_args() === 3) {
148+
return $this->mergeWhen($condition, $value, $default);
149+
}
150+
151+
return $this->mergeWhen($condition, $value);
152+
}
153+
154+
/**
155+
* Merge a value unless the current state is one of the given states.
156+
*
157+
* @param array<string|ResourceState> $states
158+
* @param mixed $value
159+
* @param mixed $default
160+
* @return \Illuminate\Http\Resources\MergeValue|mixed
161+
*/
162+
protected function mergeUnlessStateIn(array $states, $value, $default = null)
163+
{
164+
$states = array_map(fn ($state) => $this->resolveState($state), $states);
165+
166+
$condition = in_array($this->getState(), $states, true);
167+
168+
if (func_num_args() === 3) {
169+
return $this->mergeUnless($condition, $value, $default);
170+
}
171+
172+
return $this->mergeUnless($condition, $value);
173+
}
174+
133175
/**
134176
* Get the current state of the resource.
135177
* This method should be implemented by the class using this trait.

0 commit comments

Comments
 (0)